使用std::vector构造一个对象并使用它
我需要避免复制和破坏由 这个答案。
现在我将它用作指针的 std::vector ,但我无法在不删除每个对象之前调用 std::vector::clear() ,也不能将 std::auto_ptr 与 std 容器一起使用。
我想做这样的事情:
vector<MyClass> MyVec;
MyVec.push_back();
MyClass &item = MyVec.back();
这将使用默认构造函数创建一个新对象,然后我可以获得引用并使用它。
关于这个方向有什么想法吗?
已解决:我使用 @MSalters 答案和 @Moo-Juices 建议使用 C++0x 右值引用来利用 std::move 语义。基于本文。
I need to avoid the additional cost of copying and destructing the object contained by a std::vector caused by this answer.
Right now I'm using it as a std::vector of pointers, but I can't call std::vector::clear() without deleting each object before nor I can use std::auto_ptr with std containers.
I wanted to do something like this:
vector<MyClass> MyVec;
MyVec.push_back();
MyClass &item = MyVec.back();
This would create a new object with the default constructor and then I could get a reference and work with it.
Any ideas on this direction?
RESOLVED: I used @MSalters answer with @Moo-Juices suggestion to use C++0x rvalue references to take vantage of std::move semantics. Based on this article.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Boost.PointerContainer 类将管理以下内存:你。特别参见 ptr_vector。
通过容器
boost::ptr_vector
,您可以使用push_back(new T);
,并且T
元素的内存将被释放当容器超出范围时。Boost.PointerContainer classes will manage the memory for you. See especially ptr_vector.
With the container
boost::ptr_vector<T>
you can usepush_back(new T);
, and the memory forT
elements will get freed when the container goes out of scope.不存储对象,而是存储shared_ptr。这将避免对象复制,并在从向量中删除时自动销毁对象。
Instead of storing objects, store shared_ptr. This will avoid object copying, and will automatically destruct the object when removed from the vector.
快到了:
Almost there:
您可以通过调整大小来完成此操作,这将默认构造它必须添加到
向量
中的任何其他对象:但请考虑为什么需要这样做。分析是否确实表明复制对象的成本太高?它们是不可复制的吗?
You can do this with resize, which will default construct any additional objects it has to add to the
vector
:But do consider why you need to do this. Has profiling really shown that it's too expensive to copy the objects around? Are they non-copyable?