gpt4 book ai didi

c++ - 将引用定义为函数调用 - 有什么好处?

转载 作者:行者123 更新时间:2023-11-30 03:14:21 26 4
gpt4 key购买 nike

我遇到过这样的代码:

std::vector<foo> someFunction(Args args)
{
std::vector<foo> value;
/*...*/
return value;
}
std::vector<foo> someOtherFunction(OtherArgs args)
{
std::vector<foo> value;
/*...*/
return value;
}

const auto bar = someFunction(args);
const auto& rBar = someOtherFunction(otherArgs);

我想知道这些引用与否是否有任何显着差异。我已经使用计时器测试了这两个变量的性能,并没有发现任何显着的结果差异,而且这两个变量的行为方式似乎完全相同,至少表面上是这样。

其中一种更可取吗?如果是,为什么?抛开一致性论点。

抱歉,如果标题不清楚,我真的不知道该怎么调用它。

进一步挖掘

我在 Visual Studio 2015 (MSVC v140) 中检查了这两行的反汇编,发现了这一点:

非引用:

mov    edx,20h
lea rcx,[vec]
call std::vector<int, std::allocator<int> >::__autoclassinit2
lea rcx,[vec]
call someFunction
nop

引用:

lea    rcx[rbp+88h]
call someFunction
nop
lea rax,[rbp+88h]
mov qword ptr [rVec],rax

不幸的是,我的组装能力还远远不够好,无法准确理解这里发生的事情。

最佳答案

I am wondering if there is any significant difference to these being references or not.

没有。

第一个简单地初始化一个对象变量。

第二个初始化一个临时对象并将该对象绑定(bind)到一个引用。临时对象的生命周期延长到引用的生命周期(通常临时对象只存在到完整表达式的末尾)。

最后,一旦程序被优化,就没有任何区别。

Is one of these preferable

是的。 const auto bar = someFunction(args);

why?

因为它更简单,所以更容易理解。作为奖励,写的也少了。

关于c++ - 将引用定义为函数调用 - 有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57898338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com