Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost.Assign: using objects with map_list_of?

Tags:

c++

boost

stdmap

Using C++ with boost. In Boost.Assign can I use the new operator with map_list_of?

For example:

std::map<int, MyObject*> objects = boost::assign::map_list_of
       (1, new MyObject())(2, new MyObject())(3, new MyObject())

If not, is there another way to do it?

like image 927
User Avatar asked Jan 19 '23 16:01

User


2 Answers

It does work, yes; calling new just returns a pointer to MyObject, and it can be used anywhere that type is valid. HOWEVER the call to new might throw an exception, or MyObject's constructor might throw an exception, meaning your whole map of heap-allocated MyObjects will be leaked.

If you want exception safety as well as not having to bother deleting those objects, you should use a smart pointer instead:

std::map<int, boost::shared_ptr<MyObject> > objects = boost::assign::map_list_of<int, boost::shared_ptr<MyObject> >
    (1, new MyObject())
    (2, new MyObject())
    (3, new MyObject());
like image 164
eplawless Avatar answered Jan 24 '23 03:01

eplawless


Seems yes. This compiles fine with VS2010 & boost 1.47.

#include <boost\assign.hpp>
class MyObject{
public:
    MyObject(int i):m_i(i){}
private:
    int m_i;
};


int main (void)
{
    std::map<int, MyObject*> objects = boost::assign::map_list_of(1, new MyObject(1))(2, new MyObject(2))(3, new MyObject(3));
}
like image 24
RoundPi Avatar answered Jan 24 '23 03:01

RoundPi