不可复制的对象、映射和shared_ptr:复制构造函数中出错
Uncopyable object, map and shared_ptr : error in the copy constructor
我在构造不可复制的对象时遇到问题。让我们考虑以下示例:
class Uncopyable{
protected:
Uncopyable(){};
~Uncopyable(){};
private:
Uncopyable(const Uncopyable&);
Uncopyable& operator=(const Uncopyable&);
};
class Base { };
class Derived : public Base { };
class A : private Uncopyable {
public:
A(std::map<std::string, std::shared_ptr<Base>> & inMap);
private:
A(const A&);
A& operator=(const A&);
};
int main() {
std::map<std::string, std::shared_ptr<Derived>> lMap;
std::shared_ptr<A> oA(std::make_shared<A>(lMap));
}
如果我假设我的对象A是不可复制的,那么它就不起作用。作为一个指针,我希望我的对象a理解Derived是一个Base,但我得到了以下消息:
error C2664: 'A::A(const A &)' : cannot convert argument 1 from 'std::map<std::string,std::shared_ptr<Derived>,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' to 'std::map<std::string,std::shared_ptr<Base>,std::less<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>> &'
1> with
1> [
1> _Kty=std::string
1> , _Ty=std::shared_ptr<Derived>
1> ]
1> and
1> [
1> _Kty=std::string
1> , _Ty=std::shared_ptr<Base>
1> ]
谢谢。
错误与A
的不可压缩性无关,实际上不在复制构造函数中,而是在map
构造函数中。该错误与A'
构造函数采用有关
std::map<std::string, std::shared_ptr<Base>> &
而你正在通过一个:
std::map<std::string, std::shared_ptr<Derived>>
作为类型T
的左值引用的自变量只能由类型T
或从T
派生的类型(或具有operator T&
的类型)的左值来满足。但是std::map<std::string, std::shared_ptr<Derived>>
实际上并没有从std::map<std::string, std::shared_ptr<Base>>
继承——这两种类型也根本没有关联——std::map
没有跨类型构造函数。
换句话说,仅仅因为D
是B
并不意味着map<X, D>
是map<X, B>
。以这种方式,在C++类型系统中不存在类型的协方差。某些类型至少允许您从Class<D>
(例如std::shared_ptr
)构造Class<B>
,但标准容器(例如vector
、map
…)则不然
您必须更改lMap
以保持std::shared_ptr<Base>
秒,才能使其工作。它可以在内部容纳std::shared_ptr<Derived>
s,但map
类型必须匹配。
旁注,在C++11中,您不需要Uncopyable
。您可以简单地显式delete
这些操作:
A(A const& ) = delete;
A& operator=(A const& ) = delete;
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 使用strcpy将char数组的元素复制到另一个数组
- 是否可以初始化不可复制类型的成员变量(或基类)
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 复制列表初始化的隐式转换的等级是多少
- 当从函数参数中的临时值调用复制构造函数时
- 有可能在Armadillo中复制MATLAB circshift方法吗
- 复制几乎为空的数组的最快方法
- 以下示例中如何避免代码复制?C++/库达
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 为什么需要复制构造函数,在哪些情况下它们非常有用
- 不能将复制初始化与隐式转换的多个步骤一起使用
- 当有分配器意识的容器被复制/移动时,反弹分配器是否被复制/移走
- 为什么复制而不是移动数据元素?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 文件系统:复制功能的速度秘诀是什么
- 为共享 ptr 向量实现复制 c'tor?
- 具有基类唯一ptr的类的复制构造函数