c 11 – make_unique的异常感知malloc版本
在C 11中没有make_unique(不能使用C 14),虽然可以很快被嘲笑(很多答案已经在这里暗示了这样的事情):
template< typename T,typename ... Args > std::unique_ptr< T > my_make_unique (Args && ... args) { return { new T( std::forward< Args >( args )... ) }; } 如果所需的结果是在typename T上调用new / delete,这很好.在我的情况下,这不是因为我重写全局new / delete,内部将(在方便的地方)使用unique_ptr.所以相反,我正在使用malloc和各种包装器&基于malloc的分配器使STL容器在使用现场没有额外膨胀的情况下工作.我对这种方法做得很好,直到出现异常…… 基于this question到目前为止的答案,我将其作为一种可能的通用解决方案: template< typename T > struct destroy_free { void operator() (void * p) { if ( !p ) return; static_cast< T* >( p )->~T(); free( p ); } }; template< typename T,typename ... Args > auto malloc_make_unique (Args && ... args) -> std::unique_ptr< T,destroy_free< T > > { if ( auto ptr = malloc( sizeof(T) ) ) return { new ( ptr ) T( std::forward< Args >( args )... ) }; return { nullptr }; // global new would throw bad_alloc here. } 这似乎没问题,但是关于new(ptr)T(…)如何工作,而不是新的T(…),以及它如何影响任何版本的make_unique,特别是当使用自定义分配方法. 首先,我知道抛出std :: bad_alloc是不明智的,但是我相信这里适用最少意外的原则并且可以原谅新的做法(即,当分配失败而不是返回nullptr时抛出).这引出了两个问题. 1.用throw std :: bad_alloc()替换return {nullptr}是否合理? 2.要正确复制新的T(…)的行为,如果构造函数抛出然后需要捕获异常,那么可以立即释放内存然后重新抛出构造函数异常? 假设两者都是,下面是正确处理情况还是还有什么需要考虑的? template< typename T,typename ... Args > auto malloc_make_unique_v2 (Args && ... args) -> std::unique_ptr< T,destroy_free< T > > { if ( auto ptr = malloc( sizeof(T) ) ) try { return { new ( ptr ) T( std::forward< Args >( args )... ) }; } catch( ... ) { // catch constructor exceptions // assumed: memory allocated but object not constructed free( ptr ); // release memory,object was not constructed? throw; // propagate whatever the exception was during construction? } throw std::bad_alloc(); // no memory allocated,throw bad_alloc? } 编辑 – 请注意我为了简单而忽略了对齐. 解决方法
对我来说没问题. 有std::allocate_shared创建shared_ptr与自定义分配器分配的对象内存.你所做的实际上是allocate_unique,它在标准c中不存在(也许还有).也许您可以创建使用malloc / free的自定义分配器,然后实现自己的make_unique(如果没有)和allocate_unique. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |