enable_shared_from_this
// https://learn.microsoft.com/en-us/cpp/standard-library/enable-shared-from-this-class?view=msvc-170
#include <memory>
#include <iostream>
#include <cstring>
using namespace std;
struct base
// : public std::enable_shared_from_this<base>
{
char *val;
base(){
val = new char[1024];
}
~base(){
delete []val;
}
// shared_ptr<base> share_more()
base *share_more()
{
// return shared_from_this();
return this;
}
};
int main2()
{
// std::shared_ptr<base> sp2;
base *sp2;
{
// std::shared_ptr<base> sp1 = make_shared<base>();
base b; base *sp1 = &b;
sp2 = sp1->share_more();
std::strncpy(sp1->val, "hello", 1024 - 1);
}
cout << "sp2->val == " << sp2->val << endl;
return 0;
}
---
// https://learn.microsoft.com/en-us/cpp/standard-library/enable-shared-from-this-class?view=msvc-170
#include <memory>
#include <iostream>
#include <cstring>
using namespace std;
struct base
: public std::enable_shared_from_this<base>
{
char *val;
base(){
val = new char[1024];
}
~base(){
delete []val;
}
shared_ptr<base> share_more()
// base *share_more()
{
return shared_from_this();
// return this;
}
};
int main3()
{
std::shared_ptr<base> sp2;
// base *sp2;
{
std::shared_ptr<base> sp1 = make_shared<base>();
// base b; base *sp1 = &b;
sp2 = sp1->share_more();
std::strncpy(sp1->val, "hello", 1024 - 1);
}
cout << "sp2->val == " << sp2->val << endl;
return 0;
}

