【发布时间】:2013-01-03 19:06:01
【问题描述】:
我有以下课程:
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
};
我是这样使用的:
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)));
根据我的阅读,编译器自动生成了移动构造函数。
现在,当我踏入students.push_back(std::make_shared<Student>(std::move(stud2))); 这一行时,我到达了移动构造函数,这没关系。
如果我在进入该行时注释掉移动构造函数,我会到达复制构造函数。 我不明白为什么会这样。
【问题讨论】:
-
IIRC,编译器自动生成复制构造函数。移动构造函数不会自动生成。
-
移动构造函数仅在特定条件下自动生成:stackoverflow.com/questions/4943958/…
-
(我很好奇你为什么不在移动构造函数中使用初始化列表。)
-
对不起,Mat,但不知道你是什么意思,我是 C++ 新手
-
除了移动构造函数外,您在任何地方都使用
Student(...) : firstName(...) {}语法。那很奇怪。您也可以在那里使用它,并可能节省两个字符串结构。
标签: c++ visual-c++ c++11 visual-studio-2012 move-semantics