首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >unique_ptr boost等价物?

unique_ptr boost等价物?
EN

Stack Overflow用户
提问于 2010-06-02 05:37:17
回答 2查看 39.9K关注 0票数 56

boost库中是否有一些与C++1x的std::unique_ptr等效的类?我正在寻找的行为是能够拥有一个异常安全的工厂函数,就像这样…

代码语言:javascript
复制
std::unique_ptr<Base> create_base()
{
    return std::unique_ptr<Base>(new Derived);
}

void some_other_function()
{
    std::unique_ptr<Base> b = create_base();

    // Do some stuff with b that may or may not throw an exception...

    // Now b is destructed automagically.
}

编辑:现在,我正在使用这个hack,这似乎是我目前所能得到的最好的…

代码语言:javascript
复制
Base* create_base()
{
    return new Derived;
}

void some_other_function()
{
    boost::scoped_ptr<Base> b = create_base();

    // Do some stuff with b that may or may not throw an exception...

    // Now b is deleted automagically.
}
EN

回答 2

Stack Overflow用户

发布于 2010-06-02 05:39:09

interprocess库中的unique_ptr怎么样?

票数 5
EN

Stack Overflow用户

发布于 2010-06-02 23:20:37

我用过霍华德·辛纳特的unique_ptr。如果你不擅长从你的编译器中读取疯狂的元编程错误,你可能会想要避开。然而,在90%的情况下,它的行为就像unique_ptr一样。

否则,我建议将参数作为boost::scoped_ptr&传递,并在内部交换以窃取所有权。要获得unique_ptr样式返回值,请使用auto_ptr。捕获shared_ptrscoped_ptr中的auto_ptr返回值,避免直接使用auto_ptr

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2953530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档