C ++复制构造函数调用 [英] C++ copy constructor invocation
问题描述
据我所知,在以下场景中调用复制构造函数:
As far as i know, a copy constructor is invoked in the following scenarios :
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.
调用函数
默认构造函数
分配操作符。
Dtor已调用
Dtor已调用
请更正我,IIRC将发生以下呼叫顺序:
Please correct me, IIRC the following sequence of calls should occur :
1)x的构造函数称为
1) Constructor of x is called
2)ob2的构造函数称为
2) Constructor of ob2 is called
4)ob2的析构函数被称为
4) Destructor of ob2 called
5)将未命名的临时变量分配给x
5) Assign the unnamed temporary variable to x
6)销毁临时变量即调用其析构函数
6) Destroy temporary variable i.e invoke its destructor
7)销毁x即调用x的析构函数
7) Destroy x i.e invoke x's destructor
但是为什么不会调用复制构造函数,预期3。
But then why copy constructor is not invoked and also only 2 calls to dtors are there whereas i expect 3.
我知道编译器可以做优化,但是我的理解是正确的吗?
I know compiler can do optimizations, however, is my understanding correct ?
:)
尊敬
lali
推荐答案
当您以值返回时,可能不会调用复制构造函数 。有些编译器使用返回值优化功能。
A copy constructor might not be invoked when you return by value. Some compilers use return value optimization feature.
阅读返回值优化
这篇关于C ++复制构造函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!