Rule of Three in C++

一个人想着一个人 提交于 2019-12-12 01:57:18

问题


I've read that The Rule of Three, What is The Rule of Three? is summarized as follows:

If you need to explicitly declare either the destructor, copy constructor or copy assignment operator yourself, you probably need to explicitly declare all three of them.

My question is: In a C++ application, I have a class that manages resources (has a destructor that handles deleting pointers). I know that the application uses assignment operator all over the place, but I am absolutely certain that there is no usage in the application of a copy constructor, i.e., usage of the type Class c(..); Class d(c); so under these circumstances, am I still required to implement both an assignment operator and a copy constructor? Or will an assignment operator alone suffice? Is it possible that the assignment operator uses the copy constructor somehow?

Appreciate your thoughts.


回答1:


If you know that the copy constructor won't be used, you can express that by making it private and unimplemented, thus:

class C
{
private:
    C(const C&); // not implemented
};

(in C++11 you can use the new = delete syntax). That said, you should only do that if you're absolutely sure it will never be needed. Otherwise, you might be better off implementing it. It's important not to just leave it as is, as in that case the compiler will provide a default memberwise copy constructor that will do the wrong thing - it's a problem waiting to happen.

To some extent it depends on what the class is going to be used for - if you're writing a class that's part of a library, for instance, it makes much more sense to implement the copy constructor for consistency reasons. You have no idea a priori how your class is going to be used.




回答2:


I am absolutely certain that there is no usage in the application of a copy constructor, i.e., usage of the type Class c(..); Class d(c)

Are you aware that the following code

Foo c;
Foo b = c;

invokes the copy constructor and NOT the assignment operator? I'd implement the copy constructor just to be safe.




回答3:


In almost all cases, the compiler will generate these methods for you and you don't need to do anything. But, if implicitly generated copy constructor/assignment operator won't do what you want, and design-wise your class makes sense to be able to be copied, you should explicitly provide a copy ctor and assignment operator whether you use them both or not (as good practice).

If, design-wise, your class makes sense to be noncopyable, you can declare but not define the copy ctor/assignment op.



来源:https://stackoverflow.com/questions/42552832/passing-instances-of-objects-in-c-class-constructors-exit-code-134

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