gpt4 book ai didi

c++ - 返回默认构造的对象会阻止 NRVO 吗?

转载 作者:搜寻专家 更新时间:2023-10-31 01:27:11 26 4
gpt4 key购买 nike

假设我有这样一个函数:

using std::vector;

vector<int> build_vector(int n)
{
if (some_condition(n)) return {};

vector<int> out;

for(int x : something())
{
out.push_back(x);
}

return out;
}

函数开头的 return {} 是否可以防止 NRVO?我很好奇,因为这似乎等同于以下内容:

using std::vector;

vector<int> nrvo_friendly_build_vector(int n)
{
vector<int> out;

if (some_condition(n)) return out;

for(int x : something())
{
out.push_back(x);
}

return out;
}

但我不清楚在第一种情况下是否允许编译器执行 NRVO。

最佳答案

来自 https://en.cppreference.com/w/cpp/language/copy_elision

Under the following circumstances, the compilers are permitted, but not required to omit the copy and move (since C++11) construction of class objects even if the copy/move (since C++11) constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. This is an optimization: even when it takes place and the copy/move (since C++11) constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed:

  • In a return statement, when the operand is the name of a non-volatile object with automatic storage duration, which isn't a function parameter or a catch clause parameter, and which is of the same class type (ignoring cv-qualification) as the function return type. This variant of copy elision is known as NRVO, "named return value optimization".

  • ...

提前返回没有限制,因此两个版本都是 NRVO 的候选版本。

关于c++ - 返回默认构造的对象会阻止 NRVO 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53823211/

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