构造函数被调用的次数以及地址相同的原因
How many times the constructors are invoked and why the addresses are same
源代码:
#include <iostream>
#include <string>
using namespace std;
int counts = 0;
class A {
public:
A() {
cout << ">> A(" << ++counts << ") constructor" << endl;
}
A(const A& a) {
cout << ">> A(" << ++counts << ") copy constructor" << endl;
}
A& operator=(const A& a) {
cout << ">> A(" << ++counts << ") = constructor" << endl;
return *this;
}
};
A get_A()
{
A a1;
cout << "address of a1 = " << &a1 << endl;
return a1;
}
void test_1()
{
A a2 = get_A();
cout << "address of a2 = " << &a2 << endl;
}
int main()
{
test_1();
return 0;
}
输出:
>> A(1) constructor
address of a1 = 0x7fff5296daf8
address of a2 = 0x7fff5296daf8
我的问题:
1.为什么只有一个构造函数被调用?不应该调用赋值构造函数吗
2.为什么a1和a2的地址相同
返回值优化(RVO)是一种编译器优化,它可以消除将在get_a
中创建的临时对象复制到test_1
中的情况。这就是为什么两个对象都有相同的地址——它们实际上是完全相同的对象。您的编译器正在消除多余的构造和复制,而只是在适当的位置构造结果。
- 因为复制省略
- 因为复制省略
编译器不使用get_A()
的返回值来复制构造a2
,而是直接在调用站点分配返回值。
如果在编译器中关闭副本省略(GCC和Clang中的-fno-elide-constructors
),您可以看到预期的行为。
相关文章:
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 调用 lua 函数的地址为 C/C++?
- 在 Microsoft Access SQL 中调用自定义 DLL 函数时传递的内存地址无效
- 为什么使用存储在虚拟方法表中的地址调用虚拟函数的函数会返回垃圾?
- 指针在函数调用后更改其地址
- 获取要在C++中动态调用的回调函数的地址
- 地址处的 C++ 值与函数调用后的预期值不同
- NRVO不应该保证局部命名变量和调用站点变量采用相同的地址吗?
- 使用来自 Dll 的偏移地址调用成员函数
- 如何使用函数指针从其内存地址调用成员函数
- 通过已知地址调用函数?C++
- C++ 尝试通过内存中的地址调用函数时程序崩溃(如何修复?
- 从地址调用函数时,C 程序崩溃
- 如何通过dll中的地址调用函数
- 如何从成员的地址调用成员函数
- 在c/c++中通过函数在内存中的地址调用函数
- 显示 new() 在 malloc 返回的地址调用对象的构造函数的源代码
- 通过函数地址调用另一个类的函数
- 按地址调用函数
- 按地址调用函数失败