gpt4 book ai didi

c++ - 这个 C++ 指针容器安全吗?

转载 作者:太空宇宙 更新时间:2023-11-03 10:21:19 24 4
gpt4 key购买 nike

我想要一个类似于 boost 的 scoped_ptr 的安全 C++ 指针容器,但具有类似于值的复制语义。我打算在应用程序的最内层循环中将其用于非常频繁使用的类中非常少使用的元素,以获得更好的内存局部性。换句话说,我不关心这个类的性能,只要它的“内联”内存负载很小。

我从以下开始,但我不太擅长这个;以下安全吗?我是在重新发明轮子吗?如果是,我应该看哪里?

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;}
};

编辑: 是的,它的行为与正常值非常相似是有意为之的。分析表明该算法在其他方面相当有效,但有时会受到缓存未命中的阻碍。因此,我试图通过提取当前包含在值中但实际上并未在最内层循环中使用的大 blob 来减小对象的大小。我更愿意在不更改语义的情况下这样做——一个简单的模板包装器将是理想的。

最佳答案

不,不是。

您忘记了赋值运算符。

您可以通过将赋值运算符声明为私有(private)(并且不实现它)来选择禁止赋值(允许复制时很奇怪),或者您可以这样实现它:

copy_ptr& operator=(copy_ptr const& rhs)
{
using std::swap;

copy_ptr tmp(rhs);
swap(this->item, tmp.item);
return *this;
}

您还忘记了在复制构造函数中 other.item 可能为空(作为默认构造函数的结果),选择您的替代方案:

// 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) {}

对于类似值的行为,我更喜欢 2,因为值不能为 null。如果您允许无效,请在 operator->operator* 中引入 assert(item); 以确保正确性(在 Debug模式下)或抛出异常(无论您喜欢什么)。

最后,析构函数中的 item = 0 是无用的:一旦对象被销毁,您就无法在不调用未定义行为的情况下使用该对象...

还有 Roger Pate 关于常量传播更“类似值”的评论,但它更多的是语义问题而不是正确性问题。

关于c++ - 这个 C++ 指针容器安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4113125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com