引用对象的 STL 容器
我知道 STL 容器复制对象.所以说我有一个
I know STL containers copy the objects. So say I have a
list<SampleClass> l;
每次我做的时候
SampleClass t(...);
l.push_back(t);
将制作 t 的副本.如果 SampleClass 很大,那么它会非常昂贵.
a copy of t will be made. If SampleClass is large, then it will be very costly.
但是如果我将 l 声明为引用的容器,
But if I declare l as a container of references,
list<SampleClass&> l;
当我这样做
l.push_back(t);
它会避免复制对象吗?
推荐答案
遗憾的是不,它不会编译(至少使用 stlport).但是另一种方法是将指向您的对象的指针存储在容器中,这将完美地编译.
Sadly no, it won't compile (with stlport at least). But the alternative, which is to store pointers to your objects in the container, will compile perfectly fine.
这会给您的代码带来一些额外的语法干扰 - 您必须使用新的东西才能将它们插入到您的容器中.
This will leave you with a bit of extra syntactic noise around your code - you'll have to new things in order to insert them into your container.
std::list<class_type*> l;
l.push_back(new class_type);
然而,虽然现在不会复制对象,但当列表被破坏时,它们也不会自动为您清理.智能指针将为您解决这个问题,但代价是更多的句法噪音.并且由于您不能将 std::auto_ptr 放入标准容器中,因为它们无法被复制,因此您必须使用它们的重量稍重的 boost 表兄弟,共享指针.
However though the objects now won't be copied, they also won't be automatically cleaned up for you when the list is destructed. Smart pointers will solve this for you, but at the cost of even more syntactic noise. And since you can't put std::auto_ptr's in standard containers because they can't be copied, you have to use their slightly heavier-weight boost cousins, shared pointers.
std::list<boost::shared_ptr<class_type> > l;
l.push_back(boost::shared_ptr<class_type>(new class_type));
共享点确实会产生一些额外的开销,但它是最小的.
Shared pointed do incur some extra overhead, but it is minimal.
相关文章