class A
{
private:
int *const array;
public:
A()
{
array = new int[10];
}
~A()
{
delete [] array;
}
};
int main()
{
A a1;
A a2 = a1;
}
問:
這個類別無疑挖了一個深坑
請問如何保護使用者在沒看到原始碼情況下
也能寫出正確的程式碼
答:
自定義拷貝建構式和設定運算子為私有並且不實作它
class A
{
private:
int *array;
public:
A()
{
array = new int[10];
}
~A()
{
delete [] array;
}
private:
A(const A &other);
A& operator=(const A &other);
};
如果各位運氣不錯,手上編議器支援C++11
class A
{
private:
int *array;
public:
A()
{
array = new int[10];
}
~A()
{
delete [] array;
}
A(const A &other) = delete;
A& operator=(const A &other) = delete;
};
編譯器會給你一個大大的警示,說拷貝建構式和設定運算子被刪除
留言列表