为什么 C++ 自动对象优化发生在此代码中
why c++ auto object optimization is happening in this code?
为什么在这个程序中只创建了一个 A 对象?并且没有调用复制构造函数。这种优化叫什么?如果这是一个有效/已知的优化,那么对于多实例设计模式来说,它不会是一个麻烦吗?
#include <iostream>
#include <stdio.h>
using namespace std;
class A
{
public:
A () {
cout << "in-- Constructor A" << endl;
++as;
}
A (const A &a) {
cout << "in-- Copy-Constructor A" << endl;
++as;
}
~A() {
cout << "out --Constructor A" << endl;
--as;
}
A & operator=(const A &a) {
cout << "assignment" << endl;
++as;
//return *this;
}
static int as;
};
int A::as = 0;
A fxn() {
A a;
cout << "a: " << &a << endl;
return a;
}
int main() {
A b = fxn();
cout << "b: " << &b << endl;
cout << "did destructor of object a in func fxn called?" << endl;
return 0;
}
以上程序的输出
in-- Constructor A
a: 0x7fffeca3bed7
b: 0x7fffeca3bed7
did destructor of object a in func fxn called?
out --Constructor A
浏览链接 http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/它会帮助你。
这似乎是返回值优化的一个案例。这种优化在C++世界中是值得注意的,因为它被允许改变程序的可观察行为。它是为数不多的(如果不是唯一的话)允许这样做的优化之一,而且它来自返回副本被认为是弱点的日子。(使用移动语义和通常更快的机器,这现在不是一个问题。
基本上,编译器看到它将复制对象,因此它会在调用帧上为它分配空间,然后在那里构建它,而不是调用复制构造函数。
相关文章:
- C和C 中的代码优化
- 使用清理代码优化多个出口点
- 在 c++ 中从 txt 文件中提取条目的代码优化问题
- 为什么传递值参数经常使编译器更容易进行代码优化
- 来自MATLAB的代码优化直方图C
- C - 代码优化
- 代码优化子集总和
- 在代码优化过程中,C++11编译器是否会在可能的情况下将局部变量转换为右值
- C++-筛选Atkin代码优化
- 协议缓冲区 GetRepeatedField (反射) 代码优化
- C++代码优化
- 编译和代码优化
- C++ ARM 设备上代码优化的提示
- 我是否应该将 const 用于局部变量以获得更好的代码优化
- 用于并行计算的C++代码优化示例
- gcc/C++:如果CPU负载很低,那么代码优化用处不大,这是真的
- 反转每个单词在一个句子中使用c++需要代码优化我的代码片段
- 是我的编译器将适当的代码优化为无用的崩溃代码
- Arduino代码优化的多路复用LED矩阵
- 在代码优化中使用new运算符是否值得?