How does std :: variant become valueless_by_exception in this example?

this is an example inspired by an example from cppreference

struct S {
    operator int() { throw 42; }
};


int main(){
    variant<float, int> v{12.f}; // OK
    cout << std::boolalpha << v.valueless_by_exception() << "\n";
    try{
        v.emplace<1>(S()); // v may be valueless
    }
    catch(...){
    }
    cout << std::boolalpha << v.valueless_by_exception() << "\n";   
}

For one compiler, I tried to output it

false true

means that emplacemade the option become useless

I do not understand how this happened. In particular, I do not understand why it emplaceis called at all, I would expect that the program will not even call it from the moment of converting from S to the arguments of the int argument.

+4
source share
1 answer

Pay attention to the signature for the relevant overload std::variant::emplace:

template <size_t I, class... Args>
std::variant_alternative_t<I, variant>& emplace(Args&&... args);

. , S int ; emplace. int , , .

, variant , , , , , , , .

+5

Source: https://habr.com/ru/post/1689774/


All Articles