在c++类中使用大数组
Use large arrays inside c++ class
这就是我的类的外观。我的代码编译成功,但当我运行它时,它会崩溃并停止。
class Explore{
public:
Explore(ros::NodeHandle &nh, tf2_ros::Buffer &buffer);
private:
bool is_frontier(size_t mx, size_t my);
void explore_level_three();
void go_to_cell(size_t mx, size_t my);
void publish_markers_array();
void publish_markers();
costmap_2d::Costmap2DROS* global_costmap, *local_costmap;
costmap_2d::Costmap2D* global_costmap_, *local_costmap_;
ros::NodeHandle nh_;
ros::Publisher frontier_array_pub, frontier_pub;
vector<pair<size_t, size_t> >frontiers;
string global_frame, robot_base_frame;
unsigned char *global_og;
size_t size_x, size_y;
double init_wx, init_wy;
int vis[4001][4001], frontier_vis[4001][4001] ;
};
当我将vis[4001][4001], frontier_vis[4001][4001];
更改为vis[500][500], frontier_vis[500][500];
时,代码成功运行。
这是我的main
功能-
int main(int argc, char** argv) {
ros::init(argc, argv, "explore_node");
ros::NodeHandle nh("explore_node");
tf2_ros::Buffer buffer(ros::Duration(10));
tf2_ros::TransformListener tf(buffer);
Explore explore_one(nh, buffer);
return 0;
}
我该如何解决这个问题?
如何解决此问题?
可用于自动对象的内存通常非常有限。因此,您必须动态地分配所有巨大的对象。否则,您的变量可能会消耗为自动对象保留的所有内存,从而导致。。。堆栈溢出。
如果类的所有实例都是动态分配的,那么拥有巨大的成员变量就不会成为问题,但由于这种限制很难强制执行,因此通常最好不要拥有庞大的成员变量。
您的阵列vis
和frontier_vis
是巨大的。简单的解决方案:使用std::vector
。
很可能您正在堆栈上创建一个Explore
的对象,该对象将给出Segmentation Fault
。您应该在堆上动态声明对象
int main() {
Explore * obj = new Explore(...);
delete obj; //since obj is on the heap,
//you have to take care of delete. using smart pointers
//like std::unique_ptr can efficiently handle the lifetime
return 0;
}
而不是
int main() {
Explore obj(...);
return 0;
}
不过,你最好使用std::vector
。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '