C++ 三元运算符调用复制构造函数而不是移动构造函数

Oğu*_*ürk 0 c++ copy-constructor move-constructor

我正在使用 VS Code 在 Linux 中使用 g++ 进行编译和调试。

需要包括和使用:

#include <string>
#include <iostream>

using namespace std;
Run Code Online (Sandbox Code Playgroud)

这是我的类是可移动的:

class A {
public:
    A(const string& strA) : strA(strA) {}

    A(const A& a) : A(a.strA) {
    }

    A(A&& a) : A(a.strA) {
        a.strA = "";
    }

    string strA;
};
Run Code Online (Sandbox Code Playgroud)

返回 A 实例的示例函数:

A RetA() {
    A a("a");
    A b("bha");

    string ex;
    cin >> ex;
    a.strA += ex;

    return ex == "123" ? a : b;
}
Run Code Online (Sandbox Code Playgroud)

这是简单的主要内容:

int main() {
    A a(RetA());

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

RetA 函数中的返回值是复制的而不是移动的。为什么?

另一方面,如果我们在 RetA 函数中使用“explicitly if”而不是三元运算符:

A RetA() {
    A a("a");
    A b("bha");

    string ex;
    cin >> ex;
    a.strA += ex;

    if (ex == "123")
        return a;

    return b;
}
Run Code Online (Sandbox Code Playgroud)

然后它被移动而不是被复制。这已经是预期的行为。但奇怪的是,移动操作不适用于三元运算符。它应该是那样的还是VS Code等的错误或其他东西?

Jar*_*d42 6

“自动”移动return语句是有限的:

局部变量和参数自动移动

如果表达式是一个(可能带括号的)id 表达式,它命名一个变量,其类型要么是 [..]

情况并非如此return ex == "123" ? a : b;

然后正常方式完成,ex == "123" ? a : b返回一个左值,所以复制发生。

你可能会

return std::move(ex == "123" ? a : b);
Run Code Online (Sandbox Code Playgroud)

或者

return ex == "123" ? std::move(a) : std::move(b);
Run Code Online (Sandbox Code Playgroud)

有手册move

使用if允许自动移动遵循上述规则

if (ex == "123")
    return a;
else
    return b;
Run Code Online (Sandbox Code Playgroud)