复制对象的构造函数,将vector作为成员变量 [英] Copy constructor for object with vector as member variable

查看:117
本文介绍了复制对象的构造函数,将vector作为成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 vector< Object>的类 A .object_list _ 作为成员变量.

I have a class A with a vector<Object> object_list_ as a member variable.

我知道,如果我有一个指针向量,我将需要编写一个特定的副本构造函数以实现深层副本.但是,在这种情况下,由于我没有指针,因此在复制 A 类型的对象时,默认的复制构造函数也会自动调用 Object 的复制构造函数,或者 object_list _ 中的每个元素还是我必须编写自己的副本构造函数来做到这一点?

I know that if I had a vector of pointers I would have needed to write a specific copy constructor to achieve a deep copy. However, in this case, as I don't have pointers, when copying an object of type A, the default copy constructor will automatically also call the copy constructors of Object or each element in object_list_ or do I have to write my own copy constructor to do that?

推荐答案

您的类的默认副本构造函数将按照在类中声明的顺序为每个成员调用默认副本构造函数.一条经验法则是,如果不需要特殊的析构函数,则无需更改复制构造函数,复制分配,移动构造函数或移动分配.(尽管删除它们仍然有意义,具体取决于类).

The default copy constructor for your class will call the default copy constructor for each member, in the order they're declared in the class. One rule of thumb is that if you don't need a special destructor, then you don't need to change the copy constructor, copy assignment, move constructor, or move assignment either. (Though deleting them may still make sense, depending on the class).

向量的复制构造函数将使用其复制构造函数对其元素进行复制.如果它们是 pointers ,它将复制 pointers ,这意味着它们将指向与原始向量相同的数据.99%的时间就是您想要的.尽管极少数情况下,您可能希望替换类的副本构造函数以使向量做其他事情.

A vector's copy constructor will make a copy of its elements, using their copy constructors. If those are pointers, it will copy the pointers, which means they'll point at the same data as the origonal vector. 99% of the time this is what you want. Though very rarely you may want to replace your class' copy constructor to make the vector do something else.

听起来您不需要根据情况创建副本构造器.

It sounds like you don't need to make a copy constructor in your case.

这篇关于复制对象的构造函数,将vector作为成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆