【发布时间】:2017-07-23 16:15:31
【问题描述】:
假设我有这门课:
class Entity
{
private:
std::vector<Component*> _components;
public
Entity(std::vector<Component*>);
};
我这样做:
Entity* entity= new Entity( { new Drawable(), new Transform() ... } );
Entity* clone = new Entity(*entity);
_components 中的指针指向的对象会被复制吗?还是只有指针被复制到克隆?
【问题讨论】:
-
只会复制
_components中的指针。您应该遵循三(或五)规则让您的班级正确管理内存,请参阅:stackoverflow.com/questions/4172722/what-is-the-rule-of-three -
指针被复制,而不是被指向的对象。编写自定义复制构造函数。
-
我觉得你真的不知道什么时候使用指针,什么时候不使用。你有 Java/C# 背景吗?
-
我是一名学生,所以我没有太多的背景,使用组件的上下文要求它们是指针,但我会再次审查我的设计。
标签: c++ copy-constructor deep-copy