欢迎光临散文网 会员登陆 & 注册

enable_shared_from_this

2023-02-24 02:28 作者:小粉丝8  | 我要投稿

// 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;

}


enable_shared_from_this的评论 (共 条)

分享到微博请遵守国家法律