【发布时间】:2019-06-05 04:55:37
【问题描述】:
我有一个指向指针列表的指针,作为私有变量。我还有一个 getter,它返回指向列表的指针。我需要保护它免受更改。
我找不到如何使用 reinterpret_cast 或 const_cast 。
class typeA{
shared_ptr<list<shared_ptr<typeB>>> l;
public:
shared_ptr<list<shared_ptr<const typeB>>> getList(){return (l);};
};
编译器返回:
error: could not convert ‘((typeA*)this)->typeA::x’ from ‘std::shared_ptr<std::__cxx11::list<std::shared_ptr<typeB> > >’ to ‘std::shared_ptr<std::__cxx11::list<std::shared_ptr<const typeB> > >’|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
似乎const shared_ptr<list<shared_ptr<typeB>>> 和shared_ptr<const list<shared_ptr<typeB>>> 工作正常。
是否可以将l 作为一个完整的常量返回,例如:
const shared_ptr<const list<shared_ptr<const typeB>>>
或至少喜欢:
shared_ptr<list<shared_ptr<const typeB>>>
?
引用而不是指针不是一种选择。将l 声明为shared_ptr<list<shared_ptr<const typeB>>> 也不是想要的解决方案。
编辑:不再有“int”。
似乎不可能完全符合我的要求,但建议的解决方案很好。是的,复制指针是可以接受的。
糟糕的是,我没有立即输入 typeB。我知道引用相对于指针的一些优势,但我希望有一些类似的解决方案。
【问题讨论】:
-
我更好奇为什么你有一个指向容器的指针?那有什么用例?为什么你有一个指向
int的指针容器?那有什么用例? -
list<int>怎么样?为什么这不是一个想要的解决方案? -
@FantasticMrFox 除非有一些特殊要求,否则
std::vector<int>更适合 IMO。 -
我认为您可能需要get a couple of good books 并阅读有关references 的信息。并且拥有指向单个
int值的指针是毫无意义的(没有双关语的意思)。 -
@HD2000 我想你可能已经打算使用 int 作为一些更大对象的占位符了......但是如果你在展示代码之前明确解释,人们就会知道......另一方面,如果你写了
shared_ptr<list<shared_ptr<TypeB>>>,事情也会很清楚。虽然如果你这样做更好,但我什至接受在这种非常具体的情况下不预先声明TypeB,因为你打算问什么仍然很清楚......
标签: c++ constants smart-pointers private-members container-data-type