开发者

Boost.Assign: using objects with map_list_of?

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开发者_如何学Python 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));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜