[C++]拷贝构造的玄机

来源:互联网 发布:淘宝店铺装修免费模板 编辑:程序博客网 时间:2024/05/29 16:29

class B{public:    B()    {        cout << "B()" << endl;    }    ~B()    {        cout << "~B()" << endl;    }    B& operator=(const B& rhs)    {        cout << "B& operator=(const B& rhs)" << endl;        return *this;    }    B(const B& rhs)    {        cout << "B(const &B rhs)" << endl;    }    };
B f(B a){return a;}
void test1(){    B a1;    a1 = f(a1);}

一次参数,一次return,一次重载=

void test2(){    B a1;    B a2 = f(a1);}


一次参数,一次return

void test3(){    B a1;    B a2 = f(f(a1));}


如果把初始化和函数返回放一起 那么就把最后一次的拷贝构造调用省略

一次参数,两次返回

0 0