引用/非可空指针的容器

时间:2013-01-18 18:22:24

标签: c++ pointers reference type-systems

当我希望NULL不可能时,我通常使用引用而不是指针。既然我们不能有引用容器,那么只包含非空指针的容器类型应该是什么?

1 个答案:

答案 0 :(得分:10)

如果你要使用一个指针容器,你只需要使用一个指针容器,不要在其中放置任何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
}

Live demo

相关问题