简体   繁体   English

安全地将(shared_ptr的矢量转换为对象)转换为(shared_ptr的矢量转换为常量对象)

[英]Safely convert (vector of shared_ptr to objects) to (vector of shared_ptr to constant objects)

class A {};

typedef shared_ptr<const A*> AConstPtr;
typedef shared_ptr<A*> APtr;

vector<APtr> ptr;

const vector<AConstPtr>* foo()
{
    return &ptr;
}

This code does not compile, because "there is no implicit conversion from vector < Aptr > * to const vector < AConstPtr > * " Is there anyway to make this work, without creating a new vector, and without using an unsafe cast? 这段代码无法编译,因为“没有从向量< Aptr > *到const向量< AConstPtr > *的隐式转换”,是否仍然可以进行这项工作,而无需创建新的向量,也无需使用不安全的转换?

The reason why I need this is because I have a class that stores a list internally as vector < APtr > , but needs to expose a completely const version of it through its interface. 之所以需要它,是因为我有一个类在内部将列表存储为vector < APtr > ,但是需要通过其接口公开其完全const版本。

There's no way to do such a conversion since different shared_ptr s aren't related types. 由于不同的shared_ptr不是相关类型,因此无法进行这种转换。

First, are you really sure that you need to expose the implementation detail that there's an internal vector of shared pointers? 首先,您是否真的确定需要公开实现细节,因为存在共享指针的内部向量? That's really going to tie you to that implementation and it won't be subject to change without breaking API. 确实可以将您与该实现联系在一起,并且在不破坏API的情况下不会对其进行更改。

What about using @Cubbi's suggestion and having your interface be interators with begin and end methods instead? 如何使用@Cubbi的建议并使您的界面成为使用beginend方法的替代者呢? Then you can easily represent a container to the outside clients without tying yourself to vector . 然后,您可以轻松地向外部客户表示一个容器,而不必将自己束缚在vector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM