常量指针指向常量引用C++
Const pointer to const reference C++
如何将常量引用或地址存储到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
必须满足CopyAssignable
和CopyConstructible
的要求。但const
和引用都不可分配。
除了你的问题,在我看来,建议std::reference_wrapper
的解决方案并不好。因为当一个对象被删除时,它在该列表中的引用将悬而未决。最好的主意是使用智能指针。
正如UKMonkey所评论的那样,您不能直接在std容器中存储常量引用。但是,有一些std::cref
可以存储在此类容器中并包装常量引用。请注意,您需要 C++11。
编辑:请注意嗨,我是Frogatto关于使用它的警告。除非你有非常令人信服的理由使用std::cref
,否则最好坚持使用他提到的替代方案(智能指针)。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 代理对象的常量正确性
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 通过多个头文件使用常量变量
- 在cuda线程之间共享大量常量数据
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 是默认情况下分配给char数组常量的值
- 私有类型的静态常量成员
- 类似枚举的计算常量
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 为什么我可以通过引用修改常量返回
- 如何创建长度由常量参数指定的数组
- 当一个值是非常量但用常量表达式初始化时使用constexpr
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 隐式常量/非常量运算符布尔
- 非常量变量只读位置的赋值
- constexpr构造函数需要常量成员函数时出现问题