shared_array的元素为shared_ptr?

ent*_*heh 8 c++ boost shared-ptr c++11

如果我有boost::shared_array<T>(或a boost::shared_ptr<T[]>),有没有办法获得boost::shared_ptr<T>与阵列共享的内容?

例如,我可能想写:

shared_array<int> array(new int[10]);
shared_ptr<int> element = &array[2];
Run Code Online (Sandbox Code Playgroud)

我知道我不能使用&array[2],因为它只有类型int *,并且shared_ptr<int>有一个隐式构造函数将采用该类型是危险的.理想情况下shared_array<int>会有一个实例方法,如:

shared_ptr<int> element = array.shared_ptr_to(2);
Run Code Online (Sandbox Code Playgroud)

不幸的是我找不到这样的东西.有一个别名构造函数shared_ptr<int>将与另一个构造函数别名shared_ptr<T>,但它不允许别名shared_array<T>; 所以我也写不出来(它不会编译):

shared_ptr<int> element(array, &array[2]);
//Can't convert 'array' from shared_array<int> to shared_ptr<int>
Run Code Online (Sandbox Code Playgroud)

我玩的另一个选择是使用std::shared_ptr<T>(std而不是boost).专业化T[]不是标准化的,所以我想自己定义.不幸的是,我认为这实际上不可能以不破坏别名构造函数内部的方式,因为它试图将我std::shared_ptr<T[]>转换为自己的特定于实现的超类型,这是不可能的.(我目前只是从增强版继承.)这个想法的好处是我可以实现我的实例shared_ptr_to方法.

这是我尝试过的另一个想法,但我认为它不足以被接受为我们可能会在整个大型项目中使用的东西.

template<typename T>
boost::shared_ptr<T> GetElementPtr(const boost::shared_array<T> &array, size_t index) {
    //This deleter works by holding on to the underlying array until the deleter itself is deleted.
    struct {
        boost::shared_array<T> array;
        void operator()(T *) {} //No action required here.
    } deleter = { array };
    return shared_ptr<T>(&array[index], deleter);
}
Run Code Online (Sandbox Code Playgroud)

接下来我将尝试升级到Boost 1.53.0(我们目前只有1.50.0),shared_ptr<T[]>而不是使用shared_array<T>,而且总是使用boost而不是std(即使对于非数组).我希望这会有效,但我还没有机会尝试它:

shared_ptr<int[]> array(new int[10]);
shared_ptr<int> element(array, &array[2]);
Run Code Online (Sandbox Code Playgroud)

当然我还是更喜欢实例方法语法,但我想我对那个没有好处(没有修改Boost):

shared_ptr<int> element = array.shared_ptr_to(2);
Run Code Online (Sandbox Code Playgroud)

其他人有什么想法吗?

kas*_*sak 1

你正在做奇怪的事情。为什么需要shared_ptr元素?您是否希望将数组的元素传递到其他地方并阻止数组被删除?

如果是,那么比std::vector<shared_ptr<T>>更适合。该解决方案安全、标准,并且在对象移除方面具有细粒度