引用/非空指针的容器

Container of references / non-nullable pointers

本文关键字:空指针 引用      更新时间:2023-10-16

当我不希望使用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
}

现场演示