Suppose I have a class whose internal data representation is, for example, an std::string
:
class my_type {
std::string m_value;
...
};
Would it be fine if I can "move out" the internal representation of my_type
? Such ability would be done in a manner like:
class my_type {
std::string m_value;
public:
operator std::string() && {
// NOTE: ^^ ref qualifier for r-value
return std::move(m_value);
// Explicitly do std::move is used because ref-qualifiers don't apply
// to data members (m_value would still be an l-value), and (N)RVO
// would be crazy for the compiler to apply here.
}
};
...
my_type val;
std::string str1 = std::move(val);
std::string str2 = a_func_that_returns_my_type();
Specific questions:
Is moving out internal representation a BadIdea™? (e.g. leaky implementation?)
Am I abusing the use of (implicit) conversion operator? If so, should I use an explicit one? Example:
std::string str = std::move(val).get_str(); // Or auto instead of explicit std::string // Is this a GoodIdea™?
or
auto str = val.move_str_out();
Should I only define it if there's an existing conversion operator/function for l-values?
Is what I'm trying to achieve here be considered as premature optimization?
For some background info, please see:
- What is "rvalue reference for *this"? (for
&&
ref-qualifer) - Overload resolution with ref-qualifiers (a similar pattern as my code is shown here)