To briefly describe the question, it will be something like this:

When assigning a value to a wstring template, it makes a copy, or it initializes a new object and overwrites old data, precisely when assigned. Those. This code will overwrite the values, or will it allocate a new memory for the row from the heap and save the new pointer to the string?

 class someclass { private: std::wstring m_str; public: someclass() { m_str = std::wstring(L"Some old string"); m_str = std::wstring(L"Some new string"); } } 

    1 answer 1

    This code will execute exactly what you wrote: it will create an independent temporary object of type std::wstring containing your string, and then do the assignment of this object to the m_str string using a transfer assignment operator.

    A temporary object will be created "from scratch", that is, in the general case, a new memory will be allocated from the heap (if some optimization does not work, such as storing short lines directly, without allocating it to the heap).

    And the moving assignment operator can be implemented in different ways. This is an implementation detail. If the lines are stored without using a heap (short lines), then the movement will be reduced to copying. If, however, a heap is used, you can first release the old data, and then perform a move from the right side by interchanging the pointers. And you can simply make swap fields of objects. Etc. etc.

    And so two times.

    And how much clever the compiler is and how difficult it will be for him to understand that the first assignment is “not necessary” depends also on a pile of additional details (does the assignment code integrate, does the compiler know the semantics of this assignment, etc.)

    • And where will the old go? - LLENN
    • @Yami What kind of "old" are we talking about? - AnT
    • the one that lies in the class - LLENN
    • will be removed. What else does he have to do - KoVadim
    • @KoVadim: i.e. allocate memory, delete the old object, move the copy of the new object? - LLENN