Constructor called on return statement

前端 未结 3 2201
暖寄归人
暖寄归人 2021-02-19 16:47

Consider the following example:

class X {
public:
    X() = default;
    X(const X&) = default;
    X(X&&) = delete;
};

X foo() {
    X result;
             


        
3条回答
  •  南旧
    南旧 (楼主)
    2021-02-19 17:52

    result is not an lvalue after returning from foo(), but a prvalue, so it is allowed to call the move constructor.

    From CppReference:

    The following expressions are prvalue expressions:

    • a function call or an overloaded operator expression, whose return type is non-reference, such as str.substr(1, 2), str1 + str2, or it++

    It is possible that Clang detected that the return value is unused and threw it away directly, while GCC didn't.

提交回复
热议问题