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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...