"Moving" the internal representation of an object. Good or not?

Suppose I have a class whose internal data representation is, for example std::string,:

class my_type {
   std::string m_value;
   ...
};

Would it be nice if I could "infer" an internal representation my_type? This ability will be performed in such a way as:

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();

DIRECT EXAMPLE

Concrete questions:

  • Out of BadIdea ™? S internal view? (e.g. leaking implementation?)

  • Am I abusing the use of the (implicit) conversion operator? If so, should an explicit option be used? 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 define it if there is an existing conversion operator / function for l-values?

  • Am I trying to achieve what I am trying to achieve, premature optimization?


For more information see:

+4
1

BadIdea ™?

escape- , , . , , 2 , , . , , .

, .

, BadIdea ™. , , .

(, ?)

. , , . , . .

() ? , ?

, , . , . -. , , :)

+3

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


All Articles