简体   繁体   English

关于C ++中的构造函数和赋值运算符

[英]About constructors and assign operators in C++

I simply created a class like this: 我只是创建了一个这样的类:

class GreatClass
{
public:
    GreatClass(){cout<<"Default Constructor Called!\n";}
    GreatClass(GreatClass &gc){cout<<"Copy Constructor Called!\n";}
    GreatClass(const GreatClass &gc){cout<<"Copy Constructor (CONST) Called!\n";}
    ~GreatClass(){cout<<"Destructor Called.\n";}
    GreatClass& operator=(GreatClass& gc){cout<<"Assign Operator Called!";return gc;}
    const GreatClass& operator=(const GreatClass& gc){cout<<"Assign Operator (CONST) Called!";return gc;}
};

GreatClass f(GreatClass gc)
{
    return gc;
}

and in main() function, there are two versions: 在main()函数中,有两个版本:

version #1: 版本#1:

int main()
{
    GreatClass g1;
    GreatClass G = f(g1);
}

version #2: 版本#2:

int main()
{
    GreatClass g1;
    f(g1);
}

They all generates the SAME output: 它们都生成SAME输出:

Default Constructor Called!
Copy Constructor Called!
Copy Constructor Called!
Destructor Called.
Destructor Called.
Destructor Called.

I do not understand why there is nothing happening when I'm assigning f(g1) to G . 我不明白为什么当我将f(g1)分配给G时没有发生任何事情。 What constructor or operator is called at this point? 此时调用什么构造函数或运算符?

Thanks. 谢谢。

Compiler implementations are allowed to elide/remove copy constructor calls in certain cases, the example you specify is a good example use case of such a scenario. 在某些情况下,允许编译器实现删除/删除复制构造函数调用,您指定的示例是这种情况的一个很好的示例用例。 Instead of creating a temporary object and then copying it to destination object the object is created directly in the destination object and the copy constructor call is removed out. 不是创建临时对象然后将其复制到目标对象,而是直接在目标对象中创建对象,并删除复制构造函数调用。

This optimization is known as Copy elision through Return value optimization . 此优化称为复制省略通过返回值优化

Also, with C++11 move semantics through rvalue references might kick in instead of the Copy semantics. 此外,使用C ++ 11 移动语义通过右值引用可能会启动而不是复制语义。 Even with move semantics the compilers are still free to apply RVO. 即使使用移动语义,编译器仍然可以自由地应用RVO。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM