隐式复制构造函数是否复制数组数据成员?
可能的重复:
复制控制函数中如何处理 C 数组成员?< /a>
我猜测隐式复制构造函数(由编译器生成)会复制指针数据成员(如果它们被声明为指针)。
我不确定数组数据成员会发生什么。
隐式复制构造函数是否正确复制数组成员?那么赋值运算符呢?
例如:
char mCharArray[100];
int mIntArray[100];
mCharArray
和 mIntArray
能否正确复制?
Possible Duplicate:
How are C array members handled in copy control functions?
I would guess the implicit copy constructor (generated by compiler) would copy pointer data members if they are declared as pointer.
I'm not sure what happens to array data members.
Does the implicit copy constructor copy array members correctly? What about the assignment operator?
For instance:
char mCharArray[100];
int mIntArray[100];
Would the mCharArray
and mIntArray
be copied correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,是的,这就是答案。 C 中的结构体也是如此。
Yes and yes is the answer. This is also true of structs in C.
只是为了尽可能清楚地说明:
但是,潜在的令人讨厌的情况是针对指针和引用的:
希望这有助于说明问题。
考虑一种使结构更加“复制安全”的方法:
这里,复制构造函数使 X b = a 更安全、更直观,因为它为所有字符串数据创建了自己的副本,并且没有进一步依赖或连接到复制的 X 对象,但这速度较慢并且可能更浪费内存。
Just to make it as clear as possible:
BUT, the potentially nasty case is for pointers and references:
Hopefully that helps illustate the issue.
Consider one way to make the structure more "copy-safe":
Here, the copy-constructor makes
X b = a
safer and more intuitive because it makes its own copy of all the string data and has no further dependency on or connection to the copiedX
object, but this is slower and potentially more wasteful of memory.“隐式复制构造函数(由编译器生成)” - 对所有变量进行浅复制。
"implicit copy constructor(generated by compiler)" - does a shallow copy for all variables.
是的。 C/C++ 中内置提供了复制构造函数和赋值运算符。它们进行逐字节复制(这对于较大的数组不利,因为它会导致代码膨胀)。它还复制指针,但这将是浅复制(如果指针指向某个位置,则复制的指针也将指向同一位置)。
Yes. Copy constructor and Assignment operators are in-built provided in C/C++. They do byte by byte copy (which is not good for larger arrays, as it will cause code bloat). It also copies pointer but that will be shallow copy (if pointer is pointing to some location, the copied pointer will also point to same location).