In Which Situations To Delete A Pointer

后端 未结 5 1925
深忆病人
深忆病人 2021-01-17 10:55

My following question is on memory management. I have for example an int variable not allocated dynamically in a class, let\'s say invar1. And I\'m passing the memory addres

5条回答
  •  执笔经年
    2021-01-17 11:01

    just an appendix to the other answers

    You can get rid of raw pointers and forget about memory management with the help of smart pointers (shared_ptr, unique_ptr).

    The smart pointer is responsible for releasing the memory when it goes out of scope.

    Here is an example:

    #include 
    #include 
    
    class ex1{
    public:
        ex1(std::shared_ptr p_intvar1)
        {
            ptoint = p_intvar1;
            std::cout << __func__ << std::endl;
        }
        
        ~ex1()
        {
            std::cout << __func__ << std::endl;
        }
    private:
        std::shared_ptr ptoint;
    };
    
    int main()
    {
        std::shared_ptr pi(new int(42));
        std::shared_ptr objtoclass(new ex1(pi));
    
        /* 
         * when the main function returns, these smart pointers will go
         * go out of scope and delete the dynamically allocated memory
         */ 
    
        return 0;
    }
    

    Output:

    ex1
    ~ex1
    

提交回复
热议问题