Is it possible to convert an object to std::optional without move or copy constructor?

69 views Asked by At
class A {
public:
    A() {
        std::cout << "constructor called\n";
    }

    ~A() {
        std::cout << "destructor called\n";
    }

private:
    A(const A&) = delete;
    void operator=(const A&) = delete;
};

A a() {
    return A();
}

std::optional<A> check(int condition) {
    if (condition) {
        return std::make_optional(a());
    }
    return std::nullopt;
}

int main() {
    auto event = check(true);

    std::cout << "main end\n";
}

This code doesn't compile with the copy constructor deleted. If I introduce the move constructor it works, but is it possible to do it without both copy and move constructors?

check can be like this which creates the object in place and it works

std::optional<A> check(int condition) {
    if (condition) {
        return std::make_optional<A>();
    }
    return std::nullopt;
}

But I need to go call another function which creates the object

0

There are 0 answers