Take a look at the following code. If the get
method would move the string out of the member variable, what should be the value of t
?
error e = make_error(std::string{"foobar"});
std::string s = e.get();
std::string t = e.get();
You can return a reference to the member variable. It might look as follows:
const T& get() const { return val_T_int; }
The problem with that solution is, that you can't use it with non-copyable types the following way:
std::unique_ptr<...> result = make_error(...).get();
However, you can use rvalue-references for this to solve this problem. If you declare get
in the following way, the function can only be used on temporaries (and explicitly moved objects). So it's fine to move the member variable out of the object.
T get() && { return std::move(val_T_int); }