微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 ::当你知道它是安全的时候移动返回值可以解决所有这些.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐