【发布时间】:2016-07-08 03:44:05
【问题描述】:
我在 plane.h 中声明了一个向量和一个对象:
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
}
输出确认平面确实存储在向量中。
主要:
if(universe.empty()) cout << "EMPTY UNIVERSE" << endl;
表示向量没有保留值。我希望将默认值(在 plane.cpp 中定义)存储在 Universe 中。
但是,当我从 main 实例化平面时,宇宙会保留这些值
我猜它与本地副本、范围和按值传递有关,但我无法找到一种方法来实例化实现内部的默认平面,以便将其地址保留在向量中。
我也尝试过从堆中声明向量,如下所示:
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
【问题讨论】:
-
你能把这一切归结为minimal reproducible example吗?
-
全球初始化订单惨败...
-
我的猜测是您通过值传递了
universe,将Plane放入副本中,销毁副本,然后检查原件是否包含Plane,但事实并非如此。但是没有看到代码,这只是猜测。
标签: c++ vector scope implementation