Go to the top of the page

I have the following class:

class Student { private: std::string firstName; std::string lastName; public: Student():firstName(""), lastName("") { } Student(const std::string &first, const std::string &last) :firstName(first), lastName(last) { } Student(const Student &student) :firstName(student.firstName), lastName(student.lastName) { } Student(Student &&student) { firstName=std::move(student.firstName); lastName=std::move(student.lastName); } // ... getters and setters }; 

I use it as follows:

 std::vector<std::shared_ptr<Student>> students; std::shared_ptr<Student> stud1 = std::make_shared<Student>("fn1","ln1"); students.push_back(stud1); Student stud2("fn2","ln2"); students.push_back(std::make_shared<Student>(std::move(stud2))); 

From what I read, the move constructor is automatically generated by the compiler. Right now, when I enter this line students.push_back(std::make_shared<Student>(std::move(stud2))); I get to the move constructor, which is good.

If I comment out the move constructor when entering this line, I will get to the copy constructor. I do not understand why this is happening.

+4
source share
2 answers

Visual C ++ 2012 does not imply the creation of constructors for moving or moving assignment statements.

(Rules that govern movement operations, both implicitly declared and defined, have changed several times during standardization; Visual C ++ 2012 does not support a standardized (2011) set of rules.)

+3
source

In your case, you can simply declare all of these constructors =default , for example.

 class student { std::string firstname, surname; public: student(student const&) = default; student(student&&) = default; student&operator=(student const&) = default; student&operator=(student&&) = default; // etc }; 

and donโ€™t worry about the details: the compiler should figure this out and generate the appropriate call to std::string::string(string&&) (move the constructor).

EDIT Of course, this will not work with missing compilers, but if you flag "C ++ 11", you should expect a response in C ++ 11.

+1
source

All Articles