gpt4 book ai didi

c++ - 当不涉及复制/移动时,在 C++11/14 中按值返回局部变量会导致返回值由右值构造吗?

转载 作者:IT老高 更新时间:2023-10-28 12:39:36 25 4
gpt4 key购买 nike

我知道在以下情况下,编译器可以自由地移动-构造 makeA 的返回值(但也可以自由地省略拷贝或完全移动):

struct A
{
A(A&);
A(A&&);
};

A makeA()
{
A localA;
return localA;
}

我想知道的是,如果编译器在返回声明。也就是说,在下面的例子中,是否允许编译器选择A的构造函数4作为返回值?

struct B { };
struct A {
A(A&); // (1)
A(A&&); // (2)
A(B&); // (3)
A(B&&); // (4)
};

A makeA()
{
B localB;
return localB;
}

我问这个是因为在我看来,允许 A 类型的本地对象在 return 语句中被视为右值的相同逻辑也应该允许任何类型的本地对象被视为右值,但我找不到任何这种性质的例子或问题。

最佳答案

这种情况的规则在 2011 年和 2014 年之间发生了变化。编译器现在应该将 localB 视为右值。

return 语句的适用规则可在 §12.8 [class.copy]/p32 中找到,其内容为 C++14(引用 N3936,强调我的):

When the criteria for elision of a copy/move operation are met, but not for an exception-declaration, and the object to be copied is designated by an lvalue, or when the expression in a return statement is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in the body or parameter-declaration-clause of the innermost enclosing function or lambda-expression, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. If the first overload resolution fails or was not performed, or if the type of the first parameter of the selected constructor is not an rvalue reference to the object’s type (possibly cv-qualified), overload resolution is performed again, considering the object as an lvalue.

粗体子句由 CWG issue 1579 添加,明确要求在此处调用转换移动构造函数 A::A(B&&)。这是在 GCC 5 和 Clang 3.9 中实现的。

早在 2011 年,这条“先尝试右值”规则与复制省略的标准密切相关(引用 N3337):

When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue.

由于复制省略必然要求两者具有相同的类型,因此本段不适用,编译器必须使用 A::A(B&) 构造函数。

请注意,由于 CWG 1579 被视为针对 C++11 的 DR,因此即使在 C++11 模式下,编译器也应实现其解决方案。

关于c++ - 当不涉及复制/移动时,在 C++11/14 中按值返回局部变量会导致返回值由右值构造吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25875596/

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