1. 程式人生 > >C++進階:新人易入的那些坑 --5.不讓編譯器生成的函式

C++進階:新人易入的那些坑 --5.不讓編譯器生成的函式

/*
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.
*/