移动构造函数问题

Move constructor issue

本文关键字:问题 构造函数 移动      更新时间:2023-10-16

我有以下类:

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)));

据我所知,move构造函数是由编译器自动生成的。现在,当我进入这行students.push_back(std::make_shared<Student>(std::move(stud2)));时,我到达了move构造函数,这是可以的。

如果我注释掉move构造函数,当我进入那一行时,我就到达了复制构造函数。我不明白为什么会这样。

Visual c++ 2012不隐式生成move构造函数或move赋值操作符。

(在标准化过程中,关于何时隐式声明和定义move操作的规则被修改了几次;Visual c++ 2012不支持标准化(2011)规则集

在您的情况下,您可以简单地声明所有这些构造函数=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&&)(移动构造函数)的适当调用。

EDIT当然,这不适用于有缺陷的编译器,但如果您标记为"c++ 11",那么您应该期望得到c++ 11的答案。