有的时候我们需要禁止拷贝构造和赋值运算符,否则会出错:
#include <string>
#include <iostream>
using namespace std;
class A{
public:
A(const char* a)
{
str = new string(a);
cout<<"construct A ,std addr"<<str<<endl;
}
~A()
{
cout<<"destruct A ,std addr"<<str<<endl;
delete str;
}
private:
string *str;
};
int main()
{
A a1("hello");
A a2(a1);
return 0;
}
运行程序:
construct A ,std addr0x603000000040
destruct A ,std addr0x603000000040
destruct A ,std addr0x603000000040
段错误 (核心已转储)可以看到由于使用的是默认拷贝构造函数,所以在构造a2时,a2.str和a1.str指向了同一块内存,因此在析构会被释放两次,造成段错误