STL容器引用对象 [英] STL containers with reference to objects

查看:186
本文介绍了STL容器引用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道STL容器复制对象。所以说我有一个

 列表< SampleClass> l; 

每次当我做

  SampleClass t(...); 
l.push_back(t);

将复制t。如果SampleClass是大的,那将是非常昂贵的。



但如果我声明l作为引用的容器,

  list< SampleClass&> l; 

当我做

  l.push_back(t); 

它会避免复制对象吗?

解决方案

很遗憾,不会编译(至少使用stlport)。但是另一种方法是在容器中存储指向你的对象的指针,将会编译得很好。



这会给你带来一些额外的句法噪声 - 你必须有新的东西才能将它们插入你的容器。

  std :: list< class_type *> l; 
l.push_back(new class_type);

但是,现在的对象不会被复制,它们也不会被自动清理你当列表被破坏时。智能指针将为你解决这个问题,但是以更多的句法噪声为代价。因为你不能将std :: auto_ptr放在标准容器中,因为它们不能被复制,你必须使用他们稍微更重的boost表达式,共享指针。

  std :: list< boost :: shared_ptr< class_type> > l; 
l.push_back(boost :: shared_ptr< class_type>(new class_type));

共享的指针会产生一些额外的开销,但是它是最小的。


I know STL containers copy the objects. So say I have a

list<SampleClass> l;

each time when I do

SampleClass t(...);
l.push_back(t);

a copy of t will be made. If SampleClass is large, then it will be very costly.

But if I declare l as a container of references,

list<SampleClass&> l;

When I do

l.push_back(t);

Will it avoid copying the objects?

解决方案

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

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.

这篇关于STL容器引用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆