简体   繁体   中英

=delete for user defined member functions apart from constructor, assignment operator c++11

In C++11, we use "= delete" as not to allow the constructors and operator overloaded member functions to be invoked implicitly while doing some operations(change of dataype/assignment of objects).

class color{
 public:    
 color(){cout<<"color constructed called"<<endl;}
 color(int a){};
 color(float)=delete;
 color& operator = (color &a) = delete;
 virtual void paint() = delete;  //What is the use of delete in this function
 //void paint() = delete; The above virtual is not mandatory, just a generic scenario.
 virtual void paints () final {};
};

I have used delete on user defined member function in the above example. It says that we can define the paint() function, hence no other function can call it.

Want to know if there is there is any scenarios in which this type of function declaration(paint) would be useful/recommended.

So that nothing benefits from this overload.

#include <iostream>

struct Nyan {
    int omg(int x) { return x + 2; }
};

struct Meow {
    int omg(int x) { return x + 2; }
    int omg(double) = delete;
};

int main() {
    Nyan n;
    Meow m;
    std::cout << n.omg(40) << std::endl;
    std::cout << m.omg(40) << std::endl;
    std::cout << n.omg(40.5) << std::endl;
    // std::cout << m.omg(40.5) << std::endl; // commented out for a reason
}
  • Provide stricter input arguments checks:

 void foo(void *){}

 void foo(int) = delete;

 foo(0); // error
  • Mark methods as "explicitly not implemented", this may be useful when a family of classes has a certain function but this particular class does not provide it for performance or other reasons:

class my_list
{
    // you should use other container if you need constant time size
    public: size_t size(void) = delete;     
};
  • As a final step of function deprecation. Some even use a dedicated macro.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM