Boost.Assign: using objects with map_list_of?

喜欢而已 提交于 2019-12-10 20:32:19

问题


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?


回答1:


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));
}



回答2:


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());


来源:https://stackoverflow.com/questions/7531878/boost-assign-using-objects-with-map-list-of

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!