Reputation: 4392
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?
Upvotes: 0
Views: 108
Reputation: 76688
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.
Upvotes: 1