Reputation: 7253
I read the topic about smart_ptr What is a smart pointer and when should I use one?
In my case, I have a Abstract class A
and the concrete class which implement A
: C
.
C c1;
C c2;
C c3;
I would like to put these object in a container like a map
std::map<std::string, A&> mymap;
mymap["foo"] = c1;
So I can't initialize a abstract class. The solution I found on stack overflow is using ptr like
std::map<std::string, A*> mymap;
mymap["foo"] = &c1;
And I wonder if there are any type of smart_pointer that can replace the raw pointer A*
. In the example shows in the topic, there are only dynamic allocation like :
std::map<std::string, uniq_ptr<A>> mymap;
mymap["foo"] = new C();
So, is there a smart ptr to hold an adress to a stack object or should I use a raw pointer ?
Thanks
Upvotes: 0
Views: 97
Reputation: 1638
You should use raw pointers for the objects on stack.
Smart pointers essentially call delete within their destructors, and delete is needed only if you created an object via new.
On-stack objects don't require/allow calling delete, their destructors will be called automatically when they're going out of scope, and their memory will be recycled as a part of moving stack pointer towards beginning of the stack (which always happens at each function return).
Upvotes: 1