我正在阅读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;
}