当我取消注释移动构造函数 A(A&&) 时,下面的代码段会发生什么?
What does happen to the snippet below when I uncomment the move constructor A(A&&)?
下面的代码片段似乎是对的,我相信main()
中的声明A a(std::move(b).toA());
调用了隐式声明的移动构造函数A
类,因为A
没有用户定义的复制构造函数,它没有用户定义的复制赋值操作符,它没有用户定义的移动赋值操作符,也没有用户定义的析构函数(参见§12.8/9 N4140)。然而,当我取消下面的移动构造函数A(A&&) { std::cout << "move A" << 'n'; }
的注释时,我收到Illegal instruction
消息。参见实际示例。为什么会这样?
#include <iostream>
#include <memory>
class A {
public:
// A(const A&) { std::cout << "copy A" << 'n'; }
// A(A&&) { std::cout << "move A" << 'n'; }
A(std::unique_ptr<int>&& u_ptr) : u_ptr(std::move(u_ptr)) {}
const int& getInt() { return *u_ptr; }
private:
std::unique_ptr<int> u_ptr;
};
class B {
public:
B(int u_ptr) : u_ptr(new int(u_ptr)) {}
A toA() && { return A(std::move(u_ptr)); }
private:
std::unique_ptr<int> u_ptr;
};
int main() {
B b(-1);
A a(std::move(b).toA());
std::cout << a.getInt() << 'n';
return 0;
}
您的move构造函数定义没有执行隐式定义的操作—它不会移动u_ptr
数据成员的构造。因此,a.u_ptr
是默认构造的,内部int*
初始化为nullptr
。然后,对a.getInt()
的调用试图解引用这个nullptr
,从而导致崩溃。
定义你的move构造函数如下所示,你的代码将正确运行
A(A&& other) : u_ptr(std::move(other.u_ptr)) { std::cout << "move A" << 'n'; }
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 0-1背包代码中的错误.我的代码中有什么错误
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 这行代码在C++类中意味着什么
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 我可以做些什么来消除或最小化这种将提供相同功能和行为的代码重复
- 以下 C++ 代码用于 -> "#define idiv(a, b) (((a) + (b) / 2) / (b))" 是什么?
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 此代码中的操作流程是什么?C/C++.
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- 此代码验证公式是什么意思?
- 需要以下代码的帮助,下面的代码有什么问题
- C++标准提案代码:什么是 N 和 P?
- C - 哈希算法代码什么都没有返回
- 将"12345678"转换为"1-234-5678",我的代码什么也没产生
- 在编译过程中,琐碎的(没有效果的)代码什么时候会被删除
- 有人能告诉我为什么这个代码什么都不打印吗