/*
Compiler silently writes 4 functions if they are not explicitly declared:
1.Copy constructor.
2.Copy Assignment Operator.
3.Destructor
4.Default constructor
*/
class OpenFile
{
public:
OpenFile(string filename)
{
cout << "Open a file" << filename << endl;
}
//方法1
//OpenFile(OpenFile& rhs) = delete;
//以下方法同样不能使用拷贝构造函数,因为拷贝构造函数没有定义函数体.
//g(OpenFile& f) { OpenFile f2(f);}
void destroyMe(delete this);//方法3
private:
//方法2
//OpenFile(OpenFile& rhs);
//OpenFile& operator=(const OpenFile& rhs);//私有组织调用copy Assignment Operator
//void writeLine(string str);
~OpenFile() {...};//private阻止调用
};
int main()
{
//另外定义构造函数,就不会再生成默认构造函数,因此编译错误
//OpenFile f;
//OpenFile f(string("Bo_file"));
//OpenFile f2(f);//如果要使得默认拷贝构造函数无效,可以使用方法1或者方法2
//OpenFile f(string("Bo_file"));
//f.destroyMe();删除两次出错
OpenFile *f = new OpenFile(string("Bo_file"));
f->destroyMe();
}
/*
Summary of Disallowing Functions
*
*1.C++11: f() = delete;
*2.C++03: Declare the function to be private, and not define it.
*3.Private destructor:stay out of stack.
*/
|