Move semantics for std :: vector member

I want me to understand this correctly. I ask him here, since I did not explicitly finance him.

For example, I have a triangle mesh class, which is basically built as follows:

class Mesh { public: struct Face { unsigned int a; unsigned int b; unsigned int c; }; //... private: std::string file; std::vector<glm::vec3> vertices; std::vector<glm::vec3> normals; std::vector<glm::vec2> texcoord; std::vector<Face> faces; } 

Since the data in the grid can be quite large, I want to implement the correct move semantics. For pointer types, I fully understand this, but to start the rvalue constructor, I need to use move, right?

For example, the rvalue constructor would be:

 Mesh::Mesh(Mesh&& other) : file(std::move(other.file)), vertices(std::move(other.vertices)), normals(std::move(other.normals)), texcoord(std::move(other.texcoord)), faces(std::move(other.faces) {} 

Note. . Before anyone notes the obvious, the application uses share_ptr in many places. But I do not want to artificially limit the use of the class.

+6
source share
1 answer

Yes, you should use std::move() in the move constructor, just like you. However, your move constructor exactly duplicates the default value. If your class does not define any of them:

  • copy constructor Assignment operator
  • Assignment operator
  • destructor

then a default move constructor will be created for you, which will do exactly what you did. You better abandon the definition and rely on the standard version.

Even if your class defines some of the above, you can ask the compiler to generate a default move constructor:

 class Mesh { public: Mesh(Mesh &&) = default; // the rest as before }; 

Thus, you do not need to define it, and it will work even if you add other participants later (without risk forgetting to add them to the manual move constructor).


Unfortunately, none of the above applies to Visual Studio 2015 or earlier, which cannot generate default move constructors and does not support = default for move operations. Therefore, if you are targeting VS <= 2015, you must specify a manual move constructor & mdash, just like you.

+14
source

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


All Articles