c++使用返回的对象初始化对象
c++ using returned object to initialize an object
我对C++的返回值机制感到困惑,我写了以下代码来证明我的操作,代码的结果(后面有"?",输出为粗体)让我感到困惑,有人能解释为什么它会这样输出吗,或者仅仅是因为我的编译器供应商(MS Visual C++)为我优化了吗?
#include <iostream>
class WInt
{
public:
WInt( int a ) : a(a){ std::cout << a << " " << "A constructor" << std::endl; }
WInt( const WInt& a )
{
std::cout << "copy constructor run" << std::endl;
this->a = a.a;
}
~WInt(){ std::cout << "WInt destructor" << std::endl; }
WInt& operator=( const WInt& v )
{
std::cout << "assignment operator" << std::endl;
this->a = v.a;
return *this;
}
friend const WInt operator+( const WInt& v1, const WInt& v2 )
{
return WInt( v1.a + v2.a );
}
private:
int a;
};
int main( int argc, char* argv[] )
{
std::cout << "-----------" << std::endl;
WInt a(1); // run constructor
WInt b(2); // run constructor
std::cout << "-----------" << std::endl;
WInt c = a + b; // ???????????????????
std::cout << "-----------" << std::endl;
WInt d( a + b ); // ???????????????????
std::cout << "-----------" << std::endl;
c = a + b + c; // run the +, +, =, ~, ~
std::cout << "-----------" << std::endl;
WInt e = c; // run copy constructor
std::cout << "-----------" << std::endl;
return 0;
}
输出为:
-----------
1 A constructor
2 A constructor
-----------
**3 A constructor**
-----------
**3 A constructor**
-----------
3 A constructor
6 A constructor
assignment operator
WInt destructor
WInt destructor
-----------
copy constructor run
-----------
WInt destructor
WInt destructor
WInt destructor
WInt destructor
WInt destructor
这是返回值优化。您的编译器正在优化不必要的副本(尽可能优化)。
编辑:检查此问题以获得进一步解释。
相关文章:
- 用C++中的CPerson(类)类型的对象初始化STL矢量
- 对象初始化中是否允许指向此成员的指针?
- 对象初始化后在C++中显示 char 数组时的异常行为
- 为什么两种不同的对象初始化方式给出不同的输出
- (2 问题)"类"类型重新定义(即使 #pragma 一次),以及静态函数内的静态成员对象初始化?
- afxmem.cpp中的对象初始化差异
- 删除通过取消引用新对象初始化的对象
- 如何使用sregex_token_iterator对象初始化向量
- 关于默认构造函数,对象初始化/使用C++ OOP
- C++ 基元类型初始化与对象初始化
- 哪个函数负责C++全局范围内的类对象初始化?
- C++中构造函数的对象初始化出现问题
- 如何修复模板 BST 类的对象初始化
- 无法在 QML/C++ 中使用绑定对象初始化 UI
- 为什么参数可以在对象初始化时通过赋值运算符传递给构造函数?
- 类对象初始化的二维向量
- GCC:当层次结构中存在虚拟继承时,C++11 内联对象初始化(使用 "this")不起作用
- 对象初始化
- 类对象初始化
- 使用从另一个类继承的类的对象初始化成员对象