13.1.1 合成的复制构造函数 memberwise initialize问题 C++ Primer

本文探讨了C++中默认复制构造函数的行为,解释了浅拷贝与深拷贝的区别,并讨论了何时需要自定义复制构造函数。通过具体示例说明了编译器提供的默认构造函数如何处理不同类型的成员变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值