【问题标题】:boost::recursive_wrapper and std::unique_ptrboost::recursive_wrapper 和 std::unique_ptr
【发布时间】:2016-05-10 23:38:17
【问题描述】:

目前(自 C++11 以来)使用 std::unique_ptr 设计 boost::recursive_wrapper 很简单:

template< typename T >
class recursive_wrapper
{

    std::unique_ptr< T > storage;

public :

    template< typename ...Args >
    recursive_wrapper(Args &&... args)
        : storage(std::make_unique< T >(std::forward< Args >(args)...))
    { ; }

    template< typename R >
    operator R & () noexcept
    {
        return static_cast< R & >(*storage);
    }

    template< typename R >
    operator R const & () const noexcept
    {
        return static_cast< R const & >(*storage);
    }

    void
    swap(recursive_wrapper & other) noexcept
    {
        storage.swap(other.storage);
    }

};

但目前它是通过运算符::newboost::checked_delete 设计的。在现代 C++ 中使用原始 newdelete 运算符被认为是一种不好的做法。

如果目标只是 C++11 和更新版本,使用上面的 std::unique_ptr 实现 recursive_wrapper 是否有任何缺点(我的意思是编译时性能和运行时例如性能下降或其他)?如果作为要求的向后兼容性不再存在怎么办?

【问题讨论】:

    标签: c++ c++11 boost smart-pointers boost-variant


    【解决方案1】:

    我想你会发现不这样做的原因与性能无关。

    boost::recursive_wrapper 专门设计用于允许boost::variants 包含自己。我很确定,如果您检查 boost::variant 的实现,您会发现递归模板的模板扩展依赖于看起来像这样的特化:

    template<class...T> 
    struct SomeClass<boost::recursive_wrapper<boost::variant<T...>>> 
    {
        ....
    

    除非您打算重新实现 boost::variant 以使用不同的包装类,否则它们会不兼容。

    【讨论】:

    • 我不打算将recursive_wrapper 的自定义实现用于boost::variant,而是用于another implementation of variant。该实施没有这样的问题。还有其他可以想象的缺点吗?
    • @Orient 不,我不这么认为。您必须记住自定义编码复制构造函数和复制运算符 if T 支持这些操作。
    • 如果我使用 T 来定义递归结构,则它是不完整的,因此在其实例化时,recursive_wrapper&lt; T &gt; 的类型特征格式不正确。 There is workaround,我知道,我用过。
    猜你喜欢
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2017-05-15
    相关资源
    最近更新 更多