gpt4 book ai didi

c++ - 使用 std::vector< std::shared_ptr> 是反模式吗?

转载 作者:IT老高 更新时间:2023-10-28 21:34:49 26 4
gpt4 key购买 nike

很长一段时间我都在使用std::vectorstd::shared_ptr手牵手。最近开始使用std::shared_ptr<const T>每当需要指向 const 对象的指针时。没关系,因为 std::shared_ptr<T>可以转换为 std::shared_ptr<const T>然后他们共享相同的引用计数器,一切都感觉很自然。

但是当我尝试使用 std::vector< std::shared_ptr<const T> > 等结构时我遇到了麻烦。为简化起见,我将表示这两种结构:

template <class T>
using SharedPtrVector = std::vector< std::shared_ptr<T> >;

template <class T>
using SharedConstPtrVector = std::vector< std::shared_ptr<const T> >;

问题是虽然SharedPtrVectorSharedConstPtrVector非常相似,SharedConstPtrVector不能转换为 SharedPtrVector .

所以每次我想成为一个正确的const并编写一个函数,例如:

void f(const SharedConstPtrVector<T>& vec);

我无法通过 const SharedPtrVector<T>f .

我想了很多,并考虑了几个替代方案:

  1. 编写转换函数

    template <typename T>
    SharedConstPtrVector<T> toConst(const SharedPtrVector<T>&);
  2. 以通用形式编写代码:

    template <typename T>
    void f(const std::vector< std::shared_ptr<T> >& vec);

    template <typename TIterator>
    void f(TIterator begin, TIterator end);
  3. 放弃std::vector< std::shared_ptr<const T> >的想法

1. 的问题是计算开销和代码的丑陋性增加,而 2. 给代码一种“一切都是模板”的味道。

我是一个没有经验的程序员,我不想走错方向。我想听听有此问题经验的人的建议。

最佳答案

我建议审查您的设计,以确定这些对象的明确所有者。这是由于缺乏明确的所有权导致人们使用共享智能指针。

Bjarne Stroustrup 建议仅将智能指针用作最后的手段。他的建议(从最好到最差)是:

  1. 按值存储对象。
  2. 将许多对象按值存储在一个容器中。
  3. 如果没有其他方法,请使用智能指针。

Bjarne Stroustrup - The Essence of C++: With Examples in C++84, C++98, C++11, and C++14 0:37:40。

关于c++ - 使用 std::vector< std::shared_ptr<const T>> 是反模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24085931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com