如果类成员是向量,我们是否应该显式地编写一个复制构造函数? [英] Should we explicitly write a copy constructor if the class member is a vector?

查看:59
本文介绍了如果类成员是向量,我们是否应该显式地编写一个复制构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct myType {
    vector<char*> ls;
};

此处 ls 持有指向 char 的指针.如果未提供用于 myType 的用户定义的副本构造函数,那么 myType 的默认副本构造函数会做 ls 的深层副本吗?

Here ls is holding pointers to char. If a user-defined copy constructor for myType is not provided, will myType's default copy constructor do a deep copy of ls?

推荐答案

这里ls持有char的指针.如果未提供复制构造函数,默认的复制构造函数会进行深度复制吗?

Here ls is holding pointer to char. If copy constructor is not provided, will default copy constructor do the deep copy?

默认的复制构造函数将复制所有成员,即调用其各自的复制构造函数. 1 是的,一个 std :: vector (就C ++而言,没有什么特别的有关)将被正确复制.

The default copy constructor will copy all members – i.e. call their respective copy constructors.1 So yes, a std::vector (being nothing special as far as C++ is concerned) will be duly copied.

但是,向量中 char * 元素所指向的内存当然不会,因为C ++不知道也不在乎指针指向什么.

However, the memory pointed to by the char* elements inside the vector will of course not, since C++ doesn’t know and doesn’t care what the pointers point to.

但是这里的解决方案不是提供自定义副本构造函数.它使用数据结构代替原始指针( char * ).碰巧是 std :: string (或根据意图,是 std :: vector< char> ).

But the solution here isn’t to provide a custom copy constructor. It’s to use a data structure instead of raw pointers (char*) which does. And this happens to be std::string (or std::vector<char> depending on the intent).

1 这样就创建了复制操作的传递闭包 –这通常是实现深度复制的方式,但是复制操作的实现者总是可以突破的

1 Thus creating a transitive closure of the copy operation – this is how deep copying is generally implemented, but of course an implementor of the copy operation can always break out of it.

这篇关于如果类成员是向量,我们是否应该显式地编写一个复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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