C++进阶:新人易入的那些坑 --5.不让编译器生成的函数

论坛 期权论坛 脚本     
匿名技术用户   2020-12-28 15:14   68   0
/*
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.
*/

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP