unique_ptr,移动构造函数,以及为什么总是尝试访问私有成员
unique_ptr, move constructor, and why always attempt to access private member
我经常遇到这个问题,我相信移动构造函数是有序的,但我认为复制构造函数是问题所在,隐藏它似乎不起作用。
代码:
template <class T>
class LinkedList{
public:
//
LinkedList() {}
LinkedList(const T &data);
LinkedList(const T &data, const LinkedList &node);
LinkedList(const LinkedList &object);
LinkedList &operator=(const LinkedList &object);
~LinkedList() {}
std::shared_ptr<LinkedList> push_back(const T& data);
private:
T data;
std::unique_ptr<LinkedList> link;
std::unique_ptr<LinkedList> LinkFactory(const LinkedList &node);
std::shared_ptr<LinkedList> CreateStartNode(const T &data);
std::shared_ptr<LinkedList> CreateNode(const T &data, const LinkedList &node);
};
发生错误的特定行是:
LinkedList<T>::LinkedList(const LinkedList<T> &object) : data(object.data),
link(std::move(object.link)) {}
我试图移动而不是复制复制构造函数内的链接,但无济于事。 如果移动构造函数是设计而不是合成的,那会更好吗?
你不能
移动常量对象,而且由于object
被声明为const,object.link
也是const。
这看起来像是一个损坏的设计,因为通常该构造函数是一个复制构造函数,但您试图将链接移出参数,这意味着您试图窃取它拥有的资源。你有一个 LinkFactory 方法,看起来你应该使用它,如果它做到了名称所承诺的。
采用lvalue
引用的构造函数是复制构造函数,而不是移动构造函数。如果引用const
则无法修改现有对象,因此无法从中移动。(你不应该删除const
,因为这会给你一个奇怪的破坏性复制语义,并且移动语义被添加到语言中以避免这种奇怪)。
由于unique_ptr
成员,您的类不可复制,因此您根本不应提供复制构造函数。您可以提供一个移动构造函数:
LinkedList<T>::LinkedList(LinkedList<T> && object) :
data(object.data), link(std::move(object.link)) {}
但是没有必要,因为隐式生成的移动构造函数会这样做(唯一的区别是数据是移动而不是复制)。
请记住,通常,命名变量无法移动,除非您明确这样做:
LinkedList<int> l1;
LinkedList<int> l2(l1); // ERROR: tries to copy
LinkedList<int> l3(std::move(l1)); // OK: explicit move
您要实现的语义是什么? 在您的副本中构造函数,则const
要复制的对象(即通常正确);尝试在其中移动任何东西都需要它是非恒量。 这看起来像是一个设计缺陷,但如果不是,将链接mutable
可能是答案。
我定义我的复制构造函数如下,并且使用unique_ptr没有编译时或链接错误:
LinkedList<T>::LinkedList(const LinkedList &other){
data = other.data;
link(std::move(other.link.get()));
}
我感谢大家回答这个问题。
相关文章:
- C++ 传递指向对象的指针的指针,无法访问成员
- 从不同C++类的成员变量访问成员函数
- 使用 getter 访问成员变量C++
- 如何使用包含内部类的类实例有效地从内部类访问成员?
- 通过多个类访问成员时出错
- 如何在使用对象指针时访问成员函数
- 为什么相应成员不能正确访问成员函数指针
- 从两个不同类继承的非虚拟基类的访问成员
- 如何使用 gcc 内联汇编器代码访问成员变量
- 如何使用常数向量访问成员函数
- 访问成员函数中参数的类成员
- C++嵌套结构初始化和访问成员
- 通过指向班级第一个成员的指针访问成员是不确定的行为吗?
- 如何使用C STD :: SET中的迭代器访问成员功能
- 访问成员C 时,结构的向量生成了范围的错误
- 带指针的班级访问成员
- 从聚合类访问成员变量
- 如何访问成员变量 sqlite 回调
- ctypes/C++segfault访问成员变量
- 通过父类型的指针或直接从派生类访问成员函数的差异