Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

c++ - Create shared_ptr to stack object

In my method a Player object is created like:

Player player(fullName,age);

My teacher gave us a piece of code with a constructor that takes a shared_ptr to a player object.

//constructor of the class
SomeClass(const std::shared_ptr<Socket> client, std::shared_ptr<Player> player)

Lets say we want to call the constructor of SomeClass and pass the player object we created on stack.

Is it ever safe/possible/good to create a shared_ptr from a stack object?

To make the question more understandable lets say we have two big code projects and we want to merge them so a method from one project is called from another one, should we rewrite all the files to use shared_ptr or stack objects exclusivly (for the methods that needs to be connected) or should we just create a shared_ptr to the stack object.

Why im not sure of the result:

What if the scope where the stackobject is created ends but the shared_ptr is still used and vise versa.

The stackobject gets deleted when out of scope or does it stay alive because there is still a reference to the object (in another class though)?

The shared_ptr goes out of scope and tries to delete the object, can it even though the stackobject is refering to it?

Note: I know I could just use the following and pass player

shared_ptr<Player> player{ new Player {fullName,age} };
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is it ever safe/possible/good to create a smart_ptr from a stack object?

Safe? Only if you can guarantee that the stack which created that object will only be ended after all shared_ptr's that pseudo-own it.

Possible? Sure: pass shared_ptr's constructor a deleter object that does nothing:

auto sptr = shared_ptr<Player>(&player, [](Player *) {});

When the last shared_ptr is destroyed, the deleter will be called and nothing will be deleted.

Good? Not really. As noted above, safety is not something that can be universally guaranteed in such code. Depending on your code structure, this may be legitimate. But it requires great care.

This SomeClass is expecting to claim ownership of a resource; that's why it's taking a shared_ptr. You're kind of lying to it by passing it a shared_ptr that doesn't really own the object it references. That means the onus is on you and your code structure to not violate the promise you made to SomeClass that it would have shared control over that object's lifetime.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...