若您未定义拷贝构造函数,C++在为对象进行初始化操作的时候则使用默认的拷贝构造函数,当进行默认的拷贝构造函数时,很多人说是进行浅拷贝,其实不然,这完全取决于每个成员的复制行为,并不保证一定是深拷贝或者浅拷贝 ,当然如果你想使用深拷贝,在你提供了拷贝构造函数和赋值运算符重载函数的时候你有没有想到他的副作用?还有没有优化的空间呢?
接下来我们看下MyString类的一个简单例子:
示例1:
#include <iostream>
#include <cstring>
using namespace std;
class MyString {
private:
char* str_;
int len_;
public:
MyString() : len_(1) {
str_ = new char[len_];
str_[len_ - 1] = '\0';
}
MyString(const char* s)
{
cout << "constructor" << endl;
len_ = strlen(s) + 1;
str_ = new char[len_];
for (int i = 0; i < len_; ++i)
str_[i] = s[i];