make_shared

template <class T, class... Args>
  shared_ptr<T> make_shared (Args&&... args);
Make shared_ptr

Allocates and constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr<T> that owns and stores a pointer to it (with a use count of 1).

This function uses ::new to allocate storage for the object. A similar function, allocate_shared, accepts an allocator as argument and uses it to allocate the storage.

A shared_ptr object that owns and stores a pointer to a newly allocated object of type T.

 

int main()
{
    A a;
    a.val = 100;
    using namespace std;
    std::shared_ptr<A> p0 = make_shared<A>(a);
    std::shared_ptr<A> p1 = make_shared<A>(a);
    std::shared_ptr<A> p2 = p0;
    std::shared_ptr<A> p3 = p1;
    p2->val = 200;
    printf("A.val :%d\n", a.val);
    printf("A.val :%d\n", p0->val);
    getchar();
}

posted on 2022-09-05 09:45  莫水千流  阅读(211)  评论(0编辑  收藏  举报