STL containers with reference to objects(引用对象的 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.
这篇关于引用对象的 STL 容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:引用对象的 STL 容器


- C++ 协变模板 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- 从python回调到c++的选项 2022-11-16
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01