Eam*_*nne 1 c++ smart-pointers c++11
我想要一个类似于boost的安全C++指针容器scoped_ptr,但具有类似于值的复制语义.我打算在应用程序的最内层循环中将这个用于非常少使用的类的极少使用的元素,以获得更好的内存局部性.换句话说,只要它的"内联"内存负载很小,我就不关心这个类的性能.
我从以下开始,但我不是那么熟练; 以下是安全的吗?我是否重新发明轮子,如果是这样,我应该在哪里看?
template <typename T>
class copy_ptr {
T* item;
public:
explicit copy_ptr() : item(0) {}
explicit copy_ptr(T const& existingItem) : item(new T(existingItem)) {}
copy_ptr(copy_ptr<T> const & other) : item(new T(*other.item)) {}
~copy_ptr() { delete item;item=0;}
T * get() const {return item;}
T & operator*() const {return *item;}
T * operator->() const {return item;}
};
Run Code Online (Sandbox Code Playgroud)
编辑:是的,这是故意的,它的行为与正常值非常相似.分析表明该算法在其他方面相当有效,但有时会因缓存未命中而受到阻碍.因此,我试图通过提取当前包含在值中但实际上并未在最内层循环中使用的大blob来减小对象的大小.我宁愿在没有语义变化的情况下这样做 - 一个简单的模板包装器将是理想的.
不它不是.
您忘记了分配操作员.
你可以通过声明Assignment Operator私有(而不是实现它)来选择禁止赋值(允许复制时很奇怪),或者你可以这样实现它:
copy_ptr& operator=(copy_ptr const& rhs)
{
using std::swap;
copy_ptr tmp(rhs);
swap(this->item, tmp.item);
return *this;
}
Run Code Online (Sandbox Code Playgroud)
您还忘记了other.item可能为null 的复制构造函数(作为默认构造函数的结果),选择您的替代方法:
// 1. Remove the default constructor
// 2. Implement the default constructor as
copy_ptr(): item(new T()) {}
// 3. Implement the copy constructor as
copy_ptr(copy_ptr const& rhs): item(other.item ? new T(*other.item) : 0) {}
Run Code Online (Sandbox Code Playgroud)
对于类似于值的行为,我更喜欢2,因为值不能为null.如果你想要允许nullity,请assert(item);在两者中引入operator->并operator*确保正确性(在调试模式下)或抛出异常(无论你喜欢什么).
最后,item = 0在析构函数中是无用的:在没有调用未定义的行为的情况下,无论如何都不能使用该对象...
还有罗杰佩特关于常数传播的评论更像"价值",但它更多的是语义而不是正确性.