http://social.msdn.microsoft.com/Forums/zh/vcgeneral/thread/791dc8a1-ada1-4490-85fe-6912d4fe3734
Hi All,
I got a problem here. Somebody help me please.
To my understanding, there are two facts:
1. shallow copy = bitwise copy and deep copy = memberwise copy
2. The compiler will give us a default copy constructor if needed when we do not provide it. And this constructor is memberwise copy.
So i'm confused now:
If the default copy constructor is memberwise copy(which means deep copy), why should we define our own copy constructor? Because the default one is enough. But as we encounter the following scenario, we do need to provide our own copy constructor:
Class Test
{
int a;
char *b;
};
So could the <<C++ Primer>> wrong? Because it says the default copy constructor of C++ will do memberwise copy, but in fact, it does bitwise copy.
Or i missed something?
Please help me buddies.
Thanks.
Well, I think is a hybrid as I understand this topic: The compiler-provider copy constructor will perform a shallow copy on data types that don't provide a copy constructor themselves. Example: The compiler should provide a shallow copy of the pointer inside the following class, but it should provide a memberwise copy of the STL string:
class Test
{
char *myShallowString; //The pointer will be cloned (shallow copy)
std::string myMemberString; //The std::string's copy constructor will be used (memberwise copy)
};
So if you really analyze it, C++ truly does memberwise by default: It will call the copy constructor of a char pointer, which is one compiler-provided.
Correct. If all members of the class already provide an appropriate copy constructor, the class will behave properly, meaning in my head that C++ truly provides memberwise copy construction by default.
本文探讨了C++中默认复制构造函数的行为,解释了浅拷贝与深拷贝的区别,并讨论了何时需要自定义复制构造函数。通过具体示例说明了编译器提供的默认构造函数如何处理不同类型的成员变量。
668

被折叠的 条评论
为什么被折叠?



