gpt4 book ai didi

c++ - 从函数返回 const 对象会阻止从外部进行 move 构造吗?

转载 作者:IT老高 更新时间:2023-10-28 21:43:50 26 4
gpt4 key购买 nike

给定这个函数和函数调用:

std::string GetString() {
std::stringstream sstr;
const auto str = sstr.str();
return str;
}

const auto returnedStr = GetString();

当我将 str 声明为 const 时会省略 move 构造吗?

最佳答案

在您的情况下,returnedStr 将从 GetString() 的返回值 move 构造,但该返回值将从 str 复制构造(1)。如果 str 不是 const,则返回值将从它 move 构造。

注意,在这两种情况下,返回值优化仍然适用,因此编译器仍然可以直接在 returnedStr 的空间中构造返回值(甚至是 str 本身) >,跳过一个或两个复制/move 结构。这是由 C++11 12.8/31 授予的:

When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization. This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):

  • in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value

  • ...

  • when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move

第一个要点涵盖了返回值构造的省略,另一个要点涉及将返回值 move 到 returnedStr。请注意对“相同 cv-unqualified”类型的要求,这意味着无论 cv 限定符如何,这都有效。


(1) 请注意,如果我们讨论的是 std::string 以外的类 X,它提供了一个 move 构造函数取一个const X&&,那么返回值确实会使用这个构造函数来构造(不管它可能有什么语义)。

关于c++ - 从函数返回 const 对象会阻止从外部进行 move 构造吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25784544/

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