#include <iostream>
#include <vector>
using namespace std;
class MyClass
{
public:
MyClass()
{
cout << "MyClass
is created" << endl;
}
~MyClass()
{
cout << "MyClass
is destroyed" << endl;
}
};
class MyParent
{
public:
shared_ptr<char>
data;
//char*
data;
MyParent()
{
//data =
new char[100];
data =
make_shared<char>(100);
strcpy(data.get(), "haha");
}
~MyParent()
{
data.reset();
//delete
data;
}
};
void* operator
new(std::size_t size)
{
void*
storage = malloc(size);
return
storage;
}
void operator
delete(void* data)
{
free(data);
}
int main()
{
vector<MyParent>
vec;
{
MyParent parent;
vec.push_back(parent);
}
return 1;
}
when I use shared_ptr then memory variable 'data' is still alive when we are at 'return 1;'
instead raw pointer (char* data) will be deleted.
{ MyParent parent; vec.push_back(parent); }
because char* data of local variable of parent is trying to free char* data.
Personally I prefer to use raw pointer and try to avoid use value type of MyParent.
If I use a pointer type then
vector<MyParent*> vec;