常量指针指向常量引用C++

Const pointer to const reference C++

本文关键字:常量 C++ 引用 指针      更新时间:2023-10-16

如何将常量引用或地址存储到const someType&对象?

#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;
}

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

std::list<const int&> _list;

当您声明std::list<T> . T必须满足CopyAssignableCopyConstructible的要求。但const和引用都不可分配。


除了你的问题,在我看来,建议std::reference_wrapper的解决方案并不好。因为当一个对象被删除时,它在该列表中的引用将悬而未决。最好的主意是使用智能指针。

正如UKMonkey所评论的那样,您不能直接在std容器中存储常量引用。但是,有一些std::cref可以存储在此类容器中并包装常量引用。请注意,您需要 C++11。

编辑:请注意嗨,我是Frogatto关于使用它的警告。除非你有非常令人信服的理由使用std::cref,否则最好坚持使用他提到的替代方案(智能指针)。