在c++类中使用大数组

Use large arrays inside c++ class

本文关键字:数组 c++      更新时间:2024-09-26

这就是我的类的外观。我的代码编译成功,但当我运行它时,它会崩溃并停止。

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;
} 

我该如何解决这个问题?

如何解决此问题?

可用于自动对象的内存通常非常有限。因此,您必须动态地分配所有巨大的对象。否则,您的变量可能会消耗为自动对象保留的所有内存,从而导致。。。堆栈溢出。

如果类的所有实例都是动态分配的,那么拥有巨大的成员变量就不会成为问题,但由于这种限制很难强制执行,因此通常最好不要拥有庞大的成员变量。

您的阵列visfrontier_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