开发者

Disabling default constructor for non-POD classes

开发者 https://www.devze.com 2023-01-26 17:55 出处:网络
As far as I understand, C++ default copy constructor only behaves as expected when the class is a POD class.

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 solutio开发者_开发问答n. 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 ?


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.


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.,


No, since it is a language's requirement.


When creating a class, you have 3 possibilities: to have default copy ctor, to write your own or to disable it (with different ways to do it; inheriting from boost::noncopyable to mention one). Not that clear why compiler should warn you about choosing one of these.

0

精彩评论

暂无评论...
验证码 换一张
取 消