如何从函数返回std :: optional <myclass>?

0 c++ optional c++17

我似乎错过了一些非常简单的事情.以下不起作用:

#include <optional>

class Alpha {
    Alpha() { }
    Alpha(const Alpha& that) { }
    Alpha(Alpha&& that) { }
    ~Alpha() { }

    static std::optional<Alpha> go() {
        return Alpha();
    }
};
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

no suitable user-defined conversion from "Alpha" to "std::optional<Alpha>" exists 
T in optional<T> must satisfy the requirements of Destructible 
'return': cannot convert from 'Alpha' to 'std::optional<Alpha>'
Run Code Online (Sandbox Code Playgroud)

我错过了什么,你能解释一下原因吗?

Gui*_*cot 5

您将所有构造函数设为私有.在std::optional不能移动或复制你的类.要解决这个问题,只需这样做:

class Alpha {
public: // <--- there
    Alpha() { }
    Alpha(const Alpha& that) { }
    Alpha(Alpha&& that) { }
    ~Alpha() {}

private:
    static std::optional<Alpha> go() {
        return Alpha();
    }
};
Run Code Online (Sandbox Code Playgroud)

您也可以使用a struct,默认情况下是公共成员的类.

另外,请记住,默认的构造函数和赋值运算符通常在您刚放置空的构造函数和赋值运算符时更好,性能更高.

  • 假设OP实际上有真正的类中的任何成员,默认的复制c'tor比'Alpha(const Alpha&that){}`更好,因为它实际上会复制成员而不是默认初始化它们:) (3认同)