Creating pairs with shared_ptr


#1

Hi, pretty basic but struggling to get this right.

If I have a map like so:

map<string, shared_ptr<MyClass>> mapped;

How can I add a pair to it? I’m trying…

mapped.insert(pair<string, shared_ptr<MyClass>>("name", element));

mapped.insert(make_pair("name", element));

etc

Thanks!


#2

you can simply do:

mapped["name"] = make_shared<MyClass>();

or

mapped.insert(make_pair("name", make_shared<MyClass>()));

#3

Danke :grin:


#4

Though I take it element goes in the constructor like so?

mapped["name"] = make_shared<MyClass>(element);

mapped.insert(make_pair("name", make_shared<MyClass>(element)));

I am getting No matching constructor for initialization of ‘MyClass’


#5

It is done like so (summary):

void setup(MyClass * element) {
mapped["name"] = make_shared<MyClass>(element);
}

map<string, shared_ptr<MyClass>> mapped;

MySubClass * element = new MySubClass();
setup(element);

#7

Ah OK, think I’ve got it, but now I have a problem of trying to return both the Derived class, and also add a shared_ptr with the Base class to the map. ie.

MySubClass & addChild(string name) {
    MySubClass * element = new MySubClass(name);
    mapped[name] = shared_ptr<MyClass>(element);
    return * group;
}

Memory error…


#8

make_shared is already the constructor for MyClass no need to pass a pointer but if you have a constructor with parameters then you can call:

mapped[name] = make_shared<MyClass>(name);

for subclasses you can also do:

mapped[name] = make_shared<MySubClass>(name);

the way you did it finally is correct too. not sure what’s group in your last example so it’s hard to know what might be going on


#9

Thanks, I got it working in the end but I think I have much bigger problems now. Would be great to get your help in the thread I’m just making (it’s to do with shared_ptrs).