4

我有以下课程:

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)));我到达了移动构造函数,这没关系。

如果我在进入该行时注释掉移动构造函数,我会到达复制构造函数。我不明白为什么会这样。

4

2 回答 2

3

Visual C++ 2012 does not implicitly generate move constructors or move assignment operators.

(The rules governing when move operations are and are not implicitly declared and defined changed several times during standardization; Visual C++ 2012 does not support the standardized (2011) set of rules.)

于 2013-01-21T02:59:20.763 回答
1

在您的情况下,您可以简单地声明所有这些构造函数=default,例如

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

并且不要担心细节:编译器应该对此进行排序并生成对std::string::string(string&&)(移动构造函数)的适当调用。

编辑当然,这不适用于有缺陷的编译器,但如果你标记“C++11”,那么你应该期待一个 C++11 的答案。

于 2013-01-20T17:47:22.670 回答