簡體   English   中英

在 c++ class 內部使用大 arrays

[英]Use large arrays inside c++ class

這就是我的 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 function -

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

我該如何解決這個問題?

我該如何解決這個問題?

可用於自動對象的 memory 通常非常有限。 因此,您必須動態分配所有大對象。 否則,您的變量可能會消耗為自動對象保留的所有 memory,從而導致...堆棧溢出。

如果 class 的所有實例都是動態分配的,那么擁有巨大的成員變量將不是問題,但由於該限制難以實施,通常最好不要擁有巨大的成員變量。

您的 arrays visfrontier_vis很大。 簡單的解決方案:使用std::vector

很可能您正在創建一個 object 堆棧上的Explore ,這將給出Segmentation Fault 您應該在堆上動態聲明 object

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM