设置拷贝构造函数和赋值运算为私有可以禁用掉它们。
class TestCopy
{
public:
TestCopy();
private:
TestCopy(const TestCopy&);
const TestCopy &operator=(const TestCopy&);
};
int main()
{
TestCopy t1;
TestCopy t2(t1); //error
TestCopy t3;
t3 = t1; //error
return 0;
}
可以抽象出来一个基类,当需要禁用时,只需要继承这个基类即可:
class Nocopy
{
protected:
Nocopy() {};
~Nocopy() {};
private:
Nocopy(const Nocopy&);
const Nocopy & operator=(const Nocopy&);
};
class TestCopy : private Nocopy
{
public:
TestCopy();
};
int main()
{
TestCopy t1;
TestCopy t2(t1); //error
TestCopy t2;
t2 = t1; //error
return 0;
}