std::vector 是否使用 push_back 复制对象?

2024-05-12C/C++开发问题
4

本文介绍了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::push_back() 创建参数的副本并将其存储在向量中.如果您想在向量中存储指向对象的指针,请创建一个 std::vector 而不是 std::vector.

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 复制对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6