简体   繁体   English

用 std::make_shared 创建 object 有什么好处<my_class> () 在 C++</my_class>

[英]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.在 C++ 中,您可以创建 class 和 object 的 ZA2F2ED4F8EBC2CBB4C21A29DC40AB61 如下。

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 object,如下所示。

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?创建 shared_ptr 类型的 class object 有什么好处?

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.如果您有多个新 object 的所有者,则使用std::shared_ptr / std::make_shared希望新的 object 的寿命与多个所有者的联合寿命一样长。

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.如果有的话,如果my_class是一个非常大的 class ,您可能希望在这种情况下使用std::unique_ptr / std::make_unique ,以确保它被放置在堆上而不是堆栈上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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