Reputation: 2542
I'm having a factory method object that creates a map as follows:
// std namespace is imported
Foo* createFoo() {
map<int,int>* fooMap = new map<int,int>();
for (int i=0;i < 4;i++) {
fooMap->insert(make_pair(i+1, i+2));
}
return new Foo(fooMap);
}
The foo class is as follows:
class Foo {
private:
map<int,int>* m_fooMap;
public:
Foo(map<int,int>* fooMap) : m_fooMap(fooMap) { };
void doIt() {
cout << m_fooMap->at(1) << endl;
}
}
This seems to throw an exception if I call the doIt function. When I debugged I noticed that the map object seems to not get created and populated. How can I correctly create a map on the heap?
PS: I don't want to create the map and pass by value, I'd prefer to do it through a pointer as a learning exercise. Also, if I create the map on the stack it gets populated, but of course I can't pass it to the Foo
objects since it goes out of scope.
Upvotes: 0
Views: 224
Reputation: 227390
I would favour an approach without any explicit dynamic memory allocation:
class Foo {
private:
std::map<int,int> m_fooMap;
public:
Foo(const std::map<int,int>& fooMap) : m_fooMap(fooMap) {};
Foo(std::map<int,int>&& fooMap) : m_fooMap(std::move(fooMap)) {};
void doIt() {
cout << m_fooMap.at(1) << endl;
}
};
Foo createFoo()
{
std::map<int,int> fooMap;
for (int i=0;i < 4;i++) {
fooMap.insert(make_pair(i+1, i+2));
}
return Foo(fooMap);
}
Upvotes: 1