Const指向const引用C ++的指针

时间:2017-10-25 09:36:32

标签: c++ list reference const

如何将const引用或地址存储到#include<iostream> #include<list> const int &foo( int& a) { return a; } int main() { int a = 5; const int& p = foo(a); std::list<const int&> _list; _list.push_back(p); return 0; } 个对象?

foreach

2 个答案:

答案 0 :(得分:3)

您的代码无法编译。问题出在这里:

std::list<const int&> _list;

宣布std::list<T>时。 T必须符合CopyAssignableCopyConstructible的要求。但const和参考都不可分配。

除了你的问题,我认为std::reference_wrapper的解决方案并不好。因为当一个对象被删除时,它在该列表中的引用将会悬空。最好的想法是使用智能指针。

答案 1 :(得分:1)

如UKMonkey所评论,您无法直接在std容器中存储常量引用。但是,std::cref可以存储在这样的容器中并包装一个常量引用。请注意,您需要C ++ 11。

修改:尽管如此,请注意Hi I'm Frogatto's warning。除非你有一个非常令人信服的理由使用std::cref,否则最好坚持他提到的替代方案(智能指针)。