假定代码位于内if
块,什么都在自由存储区创建对象和做只有一个调用它之间的差异:我应该在免费商店中创建对象吗?
auto a = aFactory.createA();
int result = a->foo(5);
和返回的指针拨打电话直接?
int result = aFactory.createA()->foo(5);
性能是否有差异?哪种方法更好?
#include <iostream>
#include <memory>
class A
{
public:
int foo(int a){return a+3;}
};
class AFactory
{
public:
std::unique_ptr<A> createA(){return std::make_unique<A>();}
};
int main()
{
AFactory aFactory;
bool condition = true;
if(condition)
{
auto a = aFactory.createA();
int result = a->foo(5);
}
}
可能的重复:https://stackoverflow.com/questions/26949569/do-temp-variables-slow-down-my-program – Rakete1111
你可以看看[编译器输出](https://godbolt.org/ )。如果您看到两者之间有任何差异,我会感到惊讶 – user463035818
是的,我早些时候做过。汇编代码的某些部分在不同的地方,并且作为不熟悉这种语言的人我不确定这两种方式在结果中是否总是相同。 – trivelt