Move semantics clarification [duplicate]

一世执手 提交于 2019-12-06 09:39:43

Most semantics is not a way of moving memory. It's all about the transference of ownership of objects from one object instance to another. When you do this:

std::string str1("Some string.");
std::string str2(std::move(str1));

std::string allocates and manages a buffer of characters. Therefore, each std::string owns a buffer of memory, which contains the string itself.

The move constructor called to construct str2 will take the character buffer allocated by str1 and remove it from that object. Thus str2 now has the pointer that str1 originally allocated, and str1 doesn't have that pointer anymore. That's what move semantics is all about: transferring ownership of memory owned by an object.

If your class does not have a move constructor, std::vector will not call it. Obviously. Therefore, it cannot take advantage of any potential optimizations that having a move constructor might bring. But these optimization opportunities only exist for objects which have value semantics and which contain resources that must be managed. Otherwise, movement doesn't help you.

The general rule is to use smart pointers and container objects like vector, string, and the like to avoid having to write move constructors at all. Thus, (if your compiler properly supports generating move constructors) resource management happens automatically.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!