C++ 智能指针 const 正确性

标签 c++ constants shared-ptr

我在一个类中有几个容器,例如 vector 或 map ,其中包含 shared_ptr 指向堆上的对象。

例如

template <typename T>
class MyExample
{
public:

private:
    vector<shared_ptr<T> > vec_;
    map<shared_ptr<T>, int> map_;
};

我想要这个类的公共(public)接口(interface),有时将 shared_ptrs 返回给 const 对象(通过 shared_ptr<const T> ),有时返回 shared_ptr<T>我允许调用者改变对象。

我想要逻辑 const 正确性,所以如果我将一个方法标记为 const,它就无法更改堆上的对象。

问题:

1) 我对 shared_ptr<const T> 的互换性感到困惑和 shared_ptr<T> .当有人通过 shared_ptr<const T>进入类,我:

  • 将其存储为 shared_ptr<T>shared_ptr<const T>容器内?
  • 是否要更改 map 、 vector 类型(例如 insert_element( shared_ptr<const T> obj)?

2) 最好如下实例化类:MyExample<const int> ?这似乎过于严格,因为我永远无法返回 shared_ptr<int> ?

最佳答案

shared_ptr<T>shared_ptr<const T>不可互换的。它是一种方式 - shared_ptr<T>可转换为 shared_ptr<const T>但不是相反。

观察:

// f.cpp

#include <memory>

int main()
{
    using namespace std;

    shared_ptr<int> pint(new int(4)); // normal shared_ptr
    shared_ptr<const int> pcint = pint; // shared_ptr<const T> from shared_ptr<T>
    shared_ptr<int> pint2 = pcint; // error! comment out to compile
}

通过编译

cl /EHsc f.cpp

您还可以基于常量重载函数。你可以结合做这两个事实来做你想做的事。

关于第二个问题,MyExample<int>可能比 MyExample<const int> 更有意义.

关于C++ 智能指针 const 正确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2079750/

相关文章:

c++ - AVL树实现c++

c++ - 在定义一个充满成员的结构时,是否为该结构类型的每个变量创建了这些成员?

c++ - 是否可以锁定变量以防止在 C++ 中对其进行更改?

c++ - 在异步调用中将 shared_ptr 作为参数传递

没有 .cc 文件的 .o 文件的 C++ 编译

C#技巧——通过字符串获取常量值

c++ - Const 静态方法修改值

c++ - 使用多个 ifstreams 作为 ifstreams 的 vector

c++ - 我们可以将 char[undetermined_during_compile_time_size] 保留在 boost::shared_ptr 中吗?