根据 此页面 您可以隐式转换 将shared_ptr
更改为shared_ptr
。这很有道理。
但是,当我尝试将包含 shared_ptr
的 std::vector
转换为包含 shared_ptr
时遇到错误>。
有没有好的方法来实现这种转换呢?
According to this page you can implicitly convert shared_ptr<Foo>
to shared_ptr<const Foo>
. That makes good sense.
However, I run into an error when I try to convert a std::vector
containing shared_ptr<Foo>
to one containing shared_ptr<const Foo>
.
Is there a good way to achieve this conversion?
发布评论
评论(3)
否:std::vector > 和
std::vector >
是不同的类型,因此不能将其中一种类型的对象视为另一种类型的对象。如果您确实需要一个
std::vector; >
,您可以轻松地使用shared_ptr
创建一个与原始元素相同的元素:但是,如果您按照迭代器编写代码,那么您应该不会遇到任何问题这。也就是说,
您应该使用
这种方式,而不是使用,函数s,如果函数假定范围包含
f
只需要它获取一系列可用作指向const Foo
(或< code>shared_ptrshared_ptr
s)。当函数采用范围而不是容器时,您可以将该函数与底层数据解耦:数据实际是什么或如何存储不再重要,只要您可以按照需要使用的方式使用它即可它。
No:
std::vector<shared_ptr<Foo> >
andstd::vector<shared_ptr<const Foo> >
are different types, so you can't treat an object of one as an object of the other type.If you really need a
std::vector<shared_ptr<const Foo> >
, you can easily create one withshared_ptr
s to the same elements as the original:However, if you write your code in terms of iterators, you shouldn't have any problem with this. That is, instead of using
you should be using
This way, the function
f
just requires that it gets a range of things that are usable as pointers toconst Foo
(orshared_ptr<const Foo>
s, if the function assumes that the range containsshared_ptr
s).When a function takes a range instead of a container, you decouple the function from the underlying data: it no longer matters what the data actually is or how it is stored, so long as you can use it in the way that you need to use it.
vector
和vector
是两种不同的类型。因此,如果没有黑客攻击或脏代码,这是不可能的。vector<TYPE>
andvector<const TYPE>
are two different types. So without a hack or dirty code it is not possible.为什么需要一个
std::vector ? >
?这转换很容易;只需使用两个迭代器构造函数
std::向量
。但在很多情况下,你不需要它:一般来说,const 正确性与动态分配无关
对象,如果你需要一个
shared_ptr
,有一个当您从中提取对象时自动转换
向量。
Why do you need an
std::vector<shared_ptr<Foo const> >
? Theconversion is easy; just use the two iterator constructor of
std::vector
. But in many cases, you won't need it: generally,const-correctness isn't relevant for dynamically allocated
objects, and if you need a
shared_ptr<Foo const>
, there's anautomatic conversion when you extract the object from the
vector.