我喜欢std :: unique_ptr。它帮助我防止内存泄漏,这非常有用。但是有一个问题:不允许复制分配和构建。C++ 11 - 复制指向抽象类型的智能指针的构造?
即使这个限制服务于程序员的安全,它也是相当有限的。如果您使用复制分配和构造将std :: unique_ptr的类作为其成员使用,则最终会出现问题。这就是为什么我创建了自己的包装与unique_ptr与复制构造和分配。下面是它的拷贝构造函数:
template<typename T, class Deleter>
PointerSmartSafe<T, Deleter>::PointerSmartSafe(PointerSmartSafe const& pointer_smart_safe_) noexcept : _m_opPointerUnique((_m_opPointerUnique == nullptr) ? new T(*_m_opPointerUnique.get()) : nullptr){
}
而这里的拷贝赋值运算符:
template<typename T, class Deleter>
PointerSmartSafe<T, Deleter>& PointerSmartSafe<T, Deleter>::operator=(PointerSmartSafe const& pointer_smart_safe_) noexcept{
_m_opPointerUnique = decltype(_m_opPointerUnique)(new T(*_m_opPointerUnique.get()));
return *this;
}
一切工作正常,直到我结束了使用抽象基类的类型(T)。我收到了以下错误消息:
error: cannot allocate an object of abstract type 'AbstractBaseClass'
这使我困惑。有没有解决方法?
当你需要copy'ing各地共享指针,你为什么不使用std :: shared_ptr的?那就是它的目的,而std :: unique_ptr不是。 – 2013-03-27 13:02:37
@cli_hlt,因为然后每个副本引用同一个对象,可能不是所需的。 – 2013-03-27 13:03:05
@Jonathan Wakely:的确如此。太多的开销也是。 – Helixirr 2013-03-27 13:04:07