C ++中的智能指针删除

时间:2018-04-08 16:21:27

标签: c++ smart-pointers

我正在阅读https://www.freertos.org/RTOS-task-notifications.html中的智能指针实现,一切都运行良好,如示例所示。但是,如果我尝试向上转换一个对象指针并使用智能指针,那么将会有一个关于被释放的对象的运行时错误投诉没有分配,有人可以告诉我发生了什么以及如何解决它?谢谢

#include <iostream>

template <class T>
class SmartPointer{
    T* ptr = nullptr;
public:
    explicit SmartPointer(T* t):ptr(t){}
     virtual ~SmartPointer(){
        std::cout<<"call delete here"<<std::endl;
        if (ptr!=NULL){
            delete (ptr);
        }
    }
    T & operator*(){
        return *ptr;
    }
    T * operator->(){
        return ptr;
    }

};



class Animal{
public:
    virtual void get_name(){};
    virtual ~Animal(){std::cout<<"animal is destroied"<<std::endl;}
};



class Dog:public Animal{
    std::string d_name;
public:
    Dog(std::string n):d_name(n){}
    virtual ~Dog(){std::cout<<"dog is destroied"<<std::endl;}
    void get_name(){std::cout<<"the name is "<<d_name<<std::endl;}
};


int main(int argc, const char * argv[]) {
// These lines will work
    SmartPointer<Animal>smt_animal_pt(new Animal);

// These lines will not work
    //    SmartPointer<Animal>smt_animal_pt(new Animal());
    //    Dog d("Dean");
    //    smt_animal_pt = &d;
    //    smt_animal_pt->get_name();

// These lines will not work as well
//        Animal *a = new Animal;
//        Dog d("Dean");
//        a = &d;
//        SmartPointer<Animal>smt_animal_pt(a);
//        smt_animal_pt->get_name();

    return 0;
}

1 个答案:

答案 0 :(得分:5)

您遇到的根本问题是您指定智能指针指向stack内存而不是heap内存。堆栈内存在离开作用域时将是空闲的,因为堆内存只能通过调用delete(或delete[]free()来释放,具体取决于如何分配)。

您应该只将智能指针分配给分配有new的内存。