抽象类、复制构造函数
在具有纯虚方法的类中或仅在派生类中定义复制构造函数/运算符 = 是否有意义?
Does it make sense to define a copy constructor / operator = in class having pure virtual method or only in derived classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果它只有纯虚拟方法(并且没有数据成员),那么,不,合成的方法很好(并且不会做任何事情)。
如果它确实有数据成员,那么您应该定义自己的复制构造函数(如果/当这样做有意义时),就像任何其他类一样。派生类实际上与此没有太大关系。
If it has only pure virtual methods (and no data members) then, no, the synthesised one is fine (and won't do anything).
If it does have data members then you should define your own copy constructor if/when it makes sense to do so, just like for any other class. Derived classes don't really have much to do with it.
像普通类一样:是的,如果您有特定的实现需求。
like normal classes: yes, if you have a specific implementation need.
如果它是您计划复制的对象,是的,这是一个好主意。如果不是,请参阅下面我的评论。
如果您的虚拟基类依赖于需要显式分配和复制的资源(缓冲区、操作系统对象等),则定义复制构造函数可以节省您在每个派生类中单独执行此操作的麻烦(此外,如果这些基础资源是私有的,则无法使用公共继承)。
例如:
If it is an object you plan on copying, yes, it's a good idea. See my comment below for when it isn't.
If your virtual base class relies on resources that need to be explicitly allocated and copied (buffers, operating system objects, etc.), defining a copy constructor saves you the trouble of doing so in every derived class separately (and, additionally, is something you couldn't do if those base resources were private, using public inheritance).
E.g.:
是的,你应该这样做。
拥有自己的类复制构造函数、复制赋值运算符和析构函数实现的规则甚至适用于抽象类。
另外,请查看三法则
Yes you should.
Rules of having your own implementations for copy constructor, copy assignment operator and destructor for a Class will apply to even an Abstract Class.
Also, have a look at Rule of Three
这取决于您的使用情况,如果您没有做任何需要精细处理复制的事情,例如复制句柄。如果需要,最好在派生类中定义复制构造函数。
It depends on your usage, if you are not doing anything that requires copying to handled delicately, e.g. copying a handle. You would be better to define a copy constructor in derived classes if required.