Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling default constructor for non-POD classes

As far as I understand, C++ default copy constructor only behaves as expected when the class is a POD class.

I would like to know if there's a solution for preventing the programmer to write code which (implicitely or not) uses the default copy constructor if the object is not POD.

I know you can always make your copy and assignement private to solve this problem but I'd like to know if there's an automated solution. For example the compiler could generate a warning in case your code generates a default copy constructor call and your class is not POD ?

The goal here is to detect the cases where I forgot to declare copy/assignement private or to manually define them.

Also do you guys know if cppcheck can do that ?

like image 230
Dinaiz Avatar asked Sep 11 '26 03:09

Dinaiz


2 Answers

In C++0x you can explicitly prevent use of special member functions like this:

struct NonCopyable {
    NonCopyable & operator=(const NonCopyable&) = delete;
    NonCopyable(const NonCopyable&) = delete;
    NonCopyable() = default;
};

See here for more details. Still manual unfortunately, but more elegant than now.

like image 171
Steve Townsend Avatar answered Sep 12 '26 18:09

Steve Townsend


The centralized way to disable default construction is to make the default constructor inaccessible.

You write: "I would like to know if there's a solution for preventing the programmer to write code which (implicitely or not) uses the default copy constructor if the object is not POD. ."

Presumably you mean you'd like the compiler to react to any default construction of any non-POD object.

Sorry, no compiler-independent way.

Reason: a great many non-POD classes, like smart pointers and containers such as std::vector, rely on default construction to be useful.

The g++ compiler has an option -Weffc++ to warn about violations of the guidelines in Scott Meyers’ Effective C++, but as far as I know – I could be wrong – this does not include your case. Can reportedly be useful, though.

Cheers & hth.,

like image 38
Cheers and hth. - Alf Avatar answered Sep 12 '26 18:09

Cheers and hth. - Alf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!