我在 plane.h 中声明了一个 vector 和一个对象:
extern Plane Default;
extern std::vector<Plane *>universe;
它们在 plane.cpp 中定义:
Plane Default("Default");
std::vector<Plane *>universe;
平面构造函数:
Plane::Plane(const std::string &label) {
/* check universe to ensure uniqueness */
std::cout << this << std:endl; //DEBUG CHECK to see what I push_back
universe.push_back(this); //ACTION to keep track of the planes
std::cout << universe.back() << std::endl; //DEBUG CHECK to ensure that it was stored correctly
}
输出确认平面确实存储在 vector 中。
主要内容:
if(universe.empty()) cout << "EMPTY UNIVERSE" << endl;
表示vector没有保留值。我希望默认值(如 plane.cpp 中所定义)存储在 Universe 中。
但是,当我从 main 实例化平面时,universe 保留值
我猜它与本地拷贝、范围和按值传递有关,但我想不出一种方法来在实现内部实例化默认平面,以便它的地址保留在 vector 中。
我也试过从堆中声明 vector ,如下所示:
extern std::vector<Plane *> *universe;
并这样定义:
std::vector<Plane *> *universe = new std::vector<Plane *>;
它只是让程序崩溃了。 我在 Code:Blocks 16.01 和 -std=C++11 中的 64 位 Vista 机器上使用 MinGW32 4.9
最佳答案
你遇到了全局初始化顺序的失败:
Plane Default("Default");
std::vector<Plane *>universe;
Default
依赖于universe
,但是构造Default
时,universe
还没有构造。
这就是为什么您一般应该避免全局。
您的情况的解决方法是更改顺序,假设它们在同一翻译单元中:
std::vector<Plane *>universe;
Plane Default("Default");
关于c++ - std::vector 不保留在实现中实例化的推回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36134321/