gpt4 book ai didi

c++ - 有 C++ 惰性指针吗?

转载 作者:太空宇宙 更新时间:2023-11-04 13:32:00 25 4
gpt4 key购买 nike

我需要一个类似 shared_ptr 的对象,但当我尝试访问它的成员时它会自动创建一个真实的对象。

例如,我有:

class Box
{
public:
unsigned int width;
unsigned int height;
Box(): width(50), height(100){}
};

std::vector< lazy<Box> > boxes;
boxes.resize(100);

// at this point boxes contain no any real Box object.
// But when I try to access box number 50, for example,
// it will be created.

std::cout << boxes[49].width;

// now vector contains one real box and 99 lazy boxes.

是否有一些实现,或者我应该自己编写?

最佳答案

自行推出非常简单。

template<typename T>
class lazy {
public:
lazy() : child(0) {}
~lazy() { delete child; }
T &operator*() {
if (!child) child = new T;
return *child;
}
// might dereference NULL pointer if unset...
// but if this is const, what else can be done?
const T &operator*() const { return *child; }
T *operator->() { return &**this; }
const T *operator->() const { return &**this; }
private:
T *child;
};

// ...

cout << boxes[49]->width;

关于c++ - 有 C++ 惰性指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31051163/

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