引用/非空指针的容器
Container of references / non-nullable pointers
当我不希望使用NULL
时,我通常使用引用而不是指针。既然不能有引用的容器,那么只包含非空指针的容器应该是什么类型呢?
如果你要使用指针容器,你只需要使用指针容器,不要在其中放置任何NULL指针,然后继续。
但是,如果您使用std::reference_wrapper
,则可以仍然有一个引用容器。例如:#include <vector>
#include <iostream>
#include <functional>
int main()
{
int x = 5;
std::vector<std::reference_wrapper<int>> v;
v.push_back(std::reference_wrapper<int>(x));
x = 6;
std::cout << v[0]; // 6
}
现场演示
相关文章:
- 运行时错误:引用绑定到类型为"int"的空指针
- C++ 取消引用指向矢量的空指针时的分段错误
- 错误 C6011:取消引用空指针"NAME"。C++
- cppcheck取消引用空指针
- 如何使用 GSL 库将雅可比矩阵引用为空指针
- 在循环迭代期间将引用保存到矢量中的空指针
- 为什么我在C++中有一个空指针取消引用
- 如何在python中创建等效的结构并使用malloc更改空指针的引用
- Cppcheck可能的空指针取消引用:
- 数组访问导致空指针取消引用
- 取消引用一个空指针数组
- 为什么 std::shared_ptr 取消引用不会引发空指针异常(或类似异常)?
- 取消引用指向指针数组的空指针
- 对字段的访问将导致空指针的解引用
- 可能的空指针解引用-否则检查它是否为空是多余的
- 为什么我的程序没有从取消引用空指针中捕获异常?
- 为什么空指针解引用不是一个异常
- 为什么解引用空指针是未定义的行为
- 解引用空指针
- 如何使用KDevelop查看在哪里引用空指针