-
Consider following code #include <iostream>
#include <memory>
using namespace std;
struct base{
~base() {
std::cout << "base(" << this << ") is destructed!\n";
}
};
struct derived: public base{
~derived(){
std::cout << "derived(" << this << ") is destructed!\n";
}
std::shared_ptr<std::string> a;
};
void test1(){
std::cout << "====== test1()\n";
base * p = new derived();
delete p;
}
void test2(){
std::cout << "====== test2()\n";
std::shared_ptr<base> p = std::make_shared<derived>();
}
int main()
{
test1();
test2();
return 0;
} and console output: ====== test1()
base(0x55894e2962c0) is destructed!
====== test2()
derived(0x55894e2962f0) is destructed!
base(0x55894e2962f0) is destructed! test1() shows that virtual destructor is needed when delete normal pointer, but test2 shows that is not needed for shared_ptr cases, why? |
Beta Was this translation helpful? Give feedback.
Answered by
ltqusst
Dec 29, 2021
Replies: 1 comment
-
answers:
https://www.geeksforgeeks.org/virtual-destruction-using-shared_ptr/ |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
ltqusst
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
answers:
https://www.geeksforgeeks.org/virtual-destruction-using-shared_ptr/