移动构造函数问题
Move constructor issue
我有以下类:
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的答案。
相关文章:
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- constexpr构造函数需要常量成员函数时出现问题
- 有关 c++ 构造函数的问题
- 关于复制构造函数的一个棘手问题
- 复制构造函数隐式转换问题
- 构造函数 (C++) 中的 char 指针参数存在问题
- C++:关于使用 Stroustrup 示例移动构造函数/赋值的问题
- 关于 std::bitset 构造函数的几个问题?
- 构造函数和 G++ 编译配方的问题
- 在 boost::variant 中类 holden 的复制构造函数存在问题
- C++ 关于两个类构造函数的问题
- 在构造函数 c++ 中初始化属性时出现问题
- 空构造函数和值传递问题
- 我是否需要在虚拟继承类的构造函数中初始化基类以解决菱形继承问题?
- 复制和赋值构造函数的问题
- 变分模板递归构造函数问题
- C++中用户定义的构造函数出现问题
- C ++回测问题:如何检查构造函数在假定失败时是否失败(给定输入的无效参数)
- C++的抽象类继承和构造函数的问题
- 错误 C2280 / 在 std::vector 中实例化对象时复制构造函数出现问题?