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?
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());
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With