C++的copy构造函数调用次数的问题
迷茫
迷茫 2017-04-17 12:09:21
0
1
700

原来在debug模式下也开了RVO,所以只调用了一次

class A {
public:
    A() {
        cout << "default constructor" << endl;
    }
    A(const A&) {
        cout << "A(const A&)" << endl;
    }
    A& operator=(const A&) {
        cout << "operator==" << endl;
        return *this;
    }
};

A getA() {
    A a;
    return a;
}

A& getAR() {
    A a;
    return a;
}

int main() {
    // A() -> A(const A&) -> A(const A&)
    cout << "getA()" << endl;
    A a = getA();
    // A() -> A(const A&)
    cout << "getAR()" << endl;
    A b = getAR();
    // A(const A&)
    cout << "Copy Test" << endl;
    A c = b;
}

主要疑问是第一个测试,我的想法是调用2次copy构造函数,一次是返回临时值的copy构造,还有一次是用返回的临时变量初始化a时候的copy构造,但为什么输出只有一次。
我在vs2015的debug模式下运行。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
Peter_Zhu

I didn’t see any verification of the copy constructor in your code (such as A b(a)), and the operator= version was used.

Secondly, such code is very problematic:

A& getAR() {  
    A a;
    return a;
}

The return value is a reference, but it refers to a temporary object a within a function. Under normal circumstances, using this reference outside will cause the program to crash directly. If you are lucky, the compiler will do something to help without crashing.

A b = getAR();
The problem with this code is: your intention is too vague. If you want to construct a brand new object b, you should write it like this:
A b(getAR());

If you want to create a reference, you should write it like this:
A &b = getAR();
Make sure that getAR() returns a reference to a valid object, not temporary within the function, otherwise If so, as mentioned above, continuing to use b will cause a crash.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!