mercredi 1 août 2018

Do I need to explicitly call a destructor here?

I've got an optional-like type (can't use optional because it's C++17):

template <typename T>
struct maybe {
    maybe()        : valid_(false) {}
    maybe(T value) : valid_(true)  { new (&value_) T(value); }

    // destructor
    ~maybe() {
        if (valid_) {
            value_.~T();
        }
    }

    // move value out of maybe
    operator T&&() && {
        valid_ = false;
        return std::move(value());
    }

    // explicit validity 
    explicit operator bool() const {
        return valid_;
    }

    T& value() {
        if (!valid_) {
            throw std::runtime_error("boom");
        }
        return value_;
    }

private:
    union {
        T value_;
    };
    bool valid_;
};

I'm curious in the operator T&& if it's improper to just move the value out, since the destructor will no longer do it. It seems like I would need to move the value to a temporary, destruct my storage, and then return. Which way is correct?

Aucun commentaire:

Enregistrer un commentaire