禁止在没有用户定义的构造函数的情况下显式复制数据成员
我有一个关于复制构造函数/复制对象的问题。
我有一个类,它有一些我不想复制的属性。
class Action : public Cloneable<Action>
{
public:
//Constructors and other methods are ommitted
std::vector<BattleCharacter*> Users;
std::vector<ActionTargetTuple> Targets;
protected:
ActionType Type;
std::string Name;
int UID;
}
我希望在复制此类对象时不复制 Users
和 Targets
向量。有没有办法在不使用自定义复制构造函数的情况下将它们显式标记为不可复制?如果没有,并且我使用自定义复制构造函数,我是否需要为从该类继承的每个类定义一个自定义复制构造函数?
I have a question about copy constructors/copying objects.
I have a class that has a few properties that I don't want to be copied.
class Action : public Cloneable<Action>
{
public:
//Constructors and other methods are ommitted
std::vector<BattleCharacter*> Users;
std::vector<ActionTargetTuple> Targets;
protected:
ActionType Type;
std::string Name;
int UID;
}
I want the Users
and Targets
vectors NOT to be copied when I make a copy of this type of object. Is there a way to mark them as explicitly not copyable without using a custom copy constructor? If not, and I use a custom copy constructor, will I need to define a custom copy constructor for each class that inherits from this one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
默认的复制构造函数将复制所有内容,所以是的 - 您将需要手动实现复制构造函数来实现此目的。由于这取代了默认的复制构造函数,因此您无需为每个继承的类定义一个复制构造函数(除非您想要不同的行为)。
The default copy constructor will copy everything, so yes - you will need to implement the copy constructor manually to achieve this. As this replaces the default copy ctor, you will not need to define one for each inherited class (unless you want different behavior).
您需要定义复制构造函数,以便可以自定义复制什么和不复制什么。
幸运的是,通过这样做,您可以告诉编译器不要自动生成默认的复制构造函数,您的复制构造函数将取代它。因此,不必担心派生类使用默认构造函数。
在解决解决方案时,请考虑此设计模式。
You will need to define the copy constructor, so you can customize what gets copied and what doesn't.
Luckily, by doing this, you're telling the compiler not to auto-generate the default copy constructor, yours will take its place. So, no worries about derived classes using the default constructor.
As you work through your solution, consider this design pattern.
您是否需要一个复制器来存储容器或返回对象之类的东西?如果没有,您可以考虑创建另一种方法来进行复制。
Do you need a copy ctor for something like containers or returning objects? If not you might consider creating another method for doing the copy.
我同意上面的答案,最好提供复制构造函数和赋值运算符,但是如果您出于某种原因不想这样做(?),请更改用户和目标的类型,作为变体,使用shared_ptr,它将阻止这些成员来自深层复制,例如:
此外,现在shared_ptr是TR1的一部分,因此可以在没有boost的情况下使用它。
I agree with answers above, better to provide copy constructor and assignment operator, but if you do not want to do so for some reason (?), change the type of Users and Targets, as variant, use shared_ptr, it will prevent those members from deep copy, for example:
Also, now shared_ptr is a part of TR1, so it could be used without boost.