我在一个类中有几个容器,例如 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/