C++: Is default copy constructor affected by presence of other constructors and destructor?

末鹿安然 提交于 2019-12-22 04:15:15

问题


As we know, if any constructor is declared (copy constructor included), default constructor (the one that takes no arguments) is not implicitly created. Does the same happen with a default copy constructor (the one that performs shallow copy of an object)? Also, does the presence of destructor affect this anyhow?


回答1:


The answers here are correct but not complete. They are correct for C++98 and C++03. In C++11 you will not get a copy constructor if you have declared a move constructor or move assignment operator. Furthermore if you have declared a copy assignment operator or a destructor, the implicit generation of the copy constructor is deprecated. 12.8 [class.copy]:

If the class definition does not explicitly declare a copy constructor, there is no user-declared move constructor, and there is no user-declared move assignment operator, a copy constructor is implicitly declared as defaulted (8.4.2). Such an implicit declaration is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.




回答2:


12.8 #4 Copying class objects

If the class definition does not explicitly declare a copy constructor, one is declared implicitly

And the destructor plays no part




回答3:


No. You'll get a default copy constructor unless you supply your own copy constructor, and the presence or absence of a destructor makes no difference.




回答4:


No. And note that

MyClass
{
    template <typename T> MyClass(const T&);
};

does not provide a copy constructor, and a default one is generated.




回答5:


The default copy constructor is always created, unless you define your own one. The constructor with no arguments isn't defined with any other constructor present to avoid calling it and therefore skipping the real constructor(s)'s code.



来源:https://stackoverflow.com/questions/5619292/c-is-default-copy-constructor-affected-by-presence-of-other-constructors-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!