我有一个:
std::vector<std::shared_ptr<T>>
Run Code Online (Sandbox Code Playgroud)
我想复制到哪一个
std::vector<std::shared_ptr<const T>>
Run Code Online (Sandbox Code Playgroud)
现在我注意到如果我这样做:
class A
{
public:
A(const std::vector<std::shared_ptr<int>>& list) : internalList(list.begin(), list.end()) {}
std::vector<std::shared_ptr<const int>> internalList;
};
Run Code Online (Sandbox Code Playgroud)
它编译得很好(clang ++ std == c ++ 14)但如果我这样做:
class A
{
public:
A(const std::vector<std::shared_ptr<int>>& list) : internalList(list) {}
std::vector<std::shared_ptr<const int>> internalList;
};
Run Code Online (Sandbox Code Playgroud)
我觉得很奇怪,当我使用复制构造函数时,它不起作用,因为它无法弄清楚从非const到const的转换?
xxxx.cpp:672:56: error: no matching constructor for initialization of 'std::vector<std::shared_ptr<const int> >'
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么请,如果我这样做(在构造函数中使用迭代器)是最好的解决方案?
首先,用不同类型实例化的类模板是完全不同的类型。那么std::shared_ptr<int>和std::shared_ptr<const int>是完全不同的类型,并且std::vector<std::shared_ptr<int>>和std::vector<std::shared_ptr<const int>>也是不同的类型,并且不能相互转换。
根据的构造函数std::vector,复制构造函数(第 5 个)采用std::vector相同类型的 a 作为其参数。这意味着 for std::vector<std::shared_ptr<const int>>,它不能 take std::vector<std::shared_ptr<int>>,它不能std::vector<std::shared_ptr<const int>>隐式转换为 。
另一方面,采用迭代器范围(第四个)的构造函数是函数模板,迭代器的类型是模板参数,它不必是指向相同类型的迭代器。如果该类型可用于构造向量,则允许是指向其他类型的迭代器。std::shared_ptr<int>可以用来构造std::shared_ptr<const int>,那就可以了。
请注意,std::shared_ptr具有复制/移动构造函数模板,可以采用std::shared_ptr不同的元素类型作为其参数。(虽然std::vector没有。)