gpt4 book ai didi

C++ 复制构造函数调用

转载 作者:可可西里 更新时间:2023-11-01 15:06:04 26 4
gpt4 key购买 nike

据我所知,复制构造函数在以下场景中被调用:

1) Pass by value
2) Return by value
3) When you create and initialize a new object with an existing object

程序如下:

#include <iostream> 
using namespace std;
class Example
{
public:
Example()
{
cout << "Default constructor called.\n";
}
Example(const Example &ob1)
{
cout << "Copy constructor called.\n";
}
Example& operator=(const Example &ob1)
{
cout << "Assignment operator called.\n";
return *this;
}
~Example()
{
cout<<"\nDtor invoked"<<endl;
}
int aa;
};

Example funct()
{
Example ob2;
ob2.aa=100;
return ob2;
}



int main()
{
Example x;
cout << "Calling funct..\n";
x = funct();
return 0;
}

输出是:

Default constructor called.

Calling funct..

Default constructor called.

Assignment operator called.

Dtor invoked

Dtor invoked

请纠正我,IIRC 应该发生以下调用顺序:

1) x 的构造函数被调用

2)调用ob2的构造函数

3) 函数返回并调用复制构造函数(将 ob2 复制到未命名的临时变量,即 funct() )

4) ob2 的析构函数调用

5) 将未命名的临时变量赋值给x

6) 销毁临时变量即调用其析构函数

7) 销毁 x 即调用 x 的析构函数

但是为什么没有调用复制构造函数,而且只有 2 次对 dtor 的调用,而我预计是 3 次。

我知道编译器可以进行优化,但是我的理解正确吗?

非常感谢:)

问候

拉里

最佳答案

当您按值 返回时,复制构造函数可能不会 被调用。一些编译器使用返回值优化功能。

Read about "Return Value Optimization"

关于C++ 复制构造函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1783350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com