c – 三元运算符的结果不是右值

前端之家收集整理的这篇文章主要介绍了c – 三元运算符的结果不是右值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果使用C 11编译器编译此程序,则向量不会移出该函数.
#include <vector>
using namespace std;
vector<int> create(bool cond) {
    vector<int> a(1);
    vector<int> b(2);

    return cond ? a : b;
}
int main() {
    vector<int> v = create(true);
    return 0;
}

如果你这样返回实例,它就被移动了.

if(cond) return a;
else return b;

这是一个demo on ideone.

我试过gcc 4.7.0和MSVC10.两者的行为方式相同.
我的猜测为什么会发生这种情况:
三元运算符类型是一个左值,因为它在执行return语句之前被求值.在这一点上a和b还没有x值(即将过期).
这个解释是否正确?

这是标准的缺陷吗?
这显然不是我的意图行为,也是我看来很常见的情况.

解决方法

以下是相关的标准引号:

12.8段32:

Copy elision is permitted in the following circumstances […]

  • 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 throwing,with conditions]
  • [when the source is a temporary,with conditions]
  • [when catching by value,with conditions]

第33段:

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. If overload resolution fails,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. [Note: This two-stage overload resolution must be performed regardless of whether copy elision will occur. It determines the constructor to be called if elision is not performed,and the selected constructor must be accessible even if the call is elided. – end note]

由于表达式返回(cond?a:b);不是一个简单的变量名称,它不符合复制检查或右值治疗的资格.也许有点不幸,但是很容易想象一下,将这个例子进一步扩展一下,直到你为编译器实现期望而头疼.

你可以明确地说明std ::当你知道它是安全的时候移动返回值可以解决所有这些.

原文链接:https://www.f2er.com/c/112087.html

猜你在找的C&C++相关文章