有没有C ++的lazy指针? [英] Is there C++ lazy pointer?
问题描述
我需要一个 shared_ptr
like对象,但当我尝试访问其成员时会自动创建一个真实对象。
例如,我有:
class Box
{
public:
unsigned int width;
无符号整数高度;
Box():width(50),height(100){}
};
std :: vector< lazy< Box> >盒子;
boxes.resize(100);
//此时,框中不包含任何实际的Box对象。
//但是当我尝试访问50号框时,例如
//会被创建。
std :: cout<<盒[49] .width;
//现在的向量包含一个实际框和99个惰性框。
是否有一些实现或者我应该自己写?
template< typename T>
class lazy {
public:
lazy():child(0){}
〜lazy(){delete child; }
T& operator *(){
if(!child)child = new T;
return * child;
}
//如果没有设置,可以解除引用NULL指针...
//但是如果这是const,还能做什么呢?
const T& operator *()const {return * child; }
T * operator->(){return& ** this; }
const T * operator->()const {return& ** this; }
private:
T * child;
};
// ...
cout<盒[49] - > width;
I need a shared_ptr
like object, but which automatically creates a real object when I try to access its members.
For example, I have:
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.
Is there some implementation, or I should to write my own?
It's very little effort to roll your own.
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 ++的lazy指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!