简体   繁体   中英

What is the advantage of creating an object with std::make_shared<my_class>() in C++

In C++, you can create a class and an object of the class as following.

class my_class {
    public:
        my_class() {}
        void my_function() {}
}

int main() {
    my_class my_cls_obj;
    my_cls_obj.my_function();
}

But you can also create a class object of the type Shared Pointer as following.

class my_class : public std::enable_shared_from_this<my_class> {
    public:
        my_class() {}
        void my_function() {}
}

int main() {
    std::make_shared<my_class>()->my_function();

    // or

    std::shared_ptr<my_class> my_cls_shr_ptr = std::make_shared<my_class>();
    my_cls_shr_ptr->my_function();
}

What is the advantage of creating a class object of the type shared_ptr?

There is none in the situation that you are showing and it would be a pessimization to use it.

std::shared_ptr / std::make_shared is meant to be used if you have multiple owners of the new object, meaning that you don't know in advance at which point in the program flow you want the object to be destroyed and that you want the new object to live as long as the union of the multiple owners' lifetimes.

If at all, you might want to use std::unique_ptr / std::make_unique in a situation like this if my_class is a very large class in order to make sure it is placed on the heap instead of the stack.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM