是std :: vector使用push_back复制对象吗? [英] Is std::vector copying the objects with a push_back?

查看:1088
本文介绍了是std :: vector使用push_back复制对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过对valgrind的大量调查,我得出结论,std :: vector创建了一个要push_back的对象的副本。

After a lot of investigations with valgrind, I've made the conclusion that std::vector makes a copy of an object you want to push_back.

真的 ?向量不能保存引用或没有副本的对象的指针?

Is that really true ? A vector cannot keep a reference or a pointer of an object without a copy ?!

感谢

推荐答案

是, std :: vector< T> :: push_back()创建参数的副本并将其存储在向量中。如果你想存储指向你的向量中的对象的指针,创建 std :: vector< whatever *> 而不是 std :: vector< whatever> ;

Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a std::vector<whatever*> instead of std::vector<whatever>.

但是,您需要确保指针引用的对象保持有效,而向量保存对它们的引用(使用RAII成语的智能指针解决问题) 。

However, you need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them (smart pointers utilizing the RAII idiom solve the problem).

这篇关于是std :: vector使用push_back复制对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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