目前(自 C++11 起)设计起来很简单 boost::recursive_wrapper
使用 std::unique_ptr
:
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);
}
};
但目前它是通过运算符 ::new
和 boost::checked_delete
设计的。在现代 C++ 中使用原始 new
和 delete
运算符被认为是一种不好的做法。
如果目标只是 C++11 和更新版本,按原样使用 std::unique_ptr
实现 recursive_wrapper
是否有任何缺点上面(我的意思是编译时性能和运行时性能下降,例如或其他)?如果作为要求的向后兼容性不再存在怎么办?
最佳答案
我想您会发现不这样做的原因与性能无关。
boost::recursive_wrapper
专门设计用于允许 boost::variant
包含它们自己。我很确定,如果您检查 boost::variant
的实现,您会发现递归模板的模板扩展依赖于看起来像这样的特化:
template<class...T>
struct SomeClass<boost::recursive_wrapper<boost::variant<T...>>>
{
....
除非您计划重新实现 boost::variant
以使用不同的包装类,否则会使它们不兼容。
关于c++ - boost::recursive_wrapper 和 std::unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35148841/