std::带有数据交换的矢量指针
std::vector pointer with data swap
在下面的代码部分中,交换后得到的内存结构是什么?会不会因为它们交换了下面的内存地址而发生泄漏?因为他们做了深度复制,这会好吗?如果这段代码被卡在一个类中,而我正在用一块动态内存交换一个工作缓冲区,该怎么办?
#include <iostream>
#include <vector>
int main()
{
std::vector<std::string> * ptr_str_vec =
new std::vector<std::string>();
ptr_str_vec->push_back("Hello");
std::vector<std::string> str_vec;
str_vec.push_back("World");
ptr_str_vec->swap(str_vec);
delete ptr_str_vec;
//What would be the resulting structures?
return 0;
}
编辑:发布了轻微错误的代码。修复了错误。
创建向量时,向量使用的底层连续数据块默认是从堆中创建的。在您的情况下,由于您没有提供分配器,所以使用默认的分配器。
int main()
{
std::vector<std::string> * ptr_str_vec =
new std::vector<std::string>(); // #^&! *ptr_str_vec is allocated from heap. vector's data block is allocated from heap.
ptr_str_vec->push_back("Hello"); // #^&! "hello" is copied onto heap block #1
std::vector<std::string> str_vec; // #^&! str_vec is allocated from stack. vector's data block is allocated from heap.
str_vec.push_back("World"); // #^&! "world" is copied onto heap block #2
ptr_str_vec->swap(str_vec); // #^&! swap is fast O(1), as it is done by swapping block #1 and #2's address. No data copy is done during swap.
delete ptr_str_vec; // #^&! delete ptr_str_vec as well as heap block #2.
//What would be the resulting structures? /
return 0; // #^&! delete str_vec as well as heap block #1
}
每个矢量中的值将被交换http://www.cplusplus.com/reference/vector/vector/swap/
我没有看到内存泄漏(除了你的程序在main结束时得到的泄漏,因为你没有删除指针),你的ptr_sr_vec指针不会改变,只有它指向的向量内的数据会改变
假设您已经熟悉了swap,是否有任何原因没有设置它,以便您可以测试输出,看看它自己做了什么?这将是向自己保证你确切知道它在做什么以及你使用它是否合适的最快方法。
在这种情况下,得到的结构简单地是ptr_str_vec
指向包含std::string("World")
的向量,而str_vec
是包含std::string("Hello")
的向量。你的例子在回答你的问题时有很多错误,特别是因为每个向量中只有一个元素(因此向量的长度相等),以及因为元素的大小完全相同(因此向量占用的内存段大致相等)。在整个项目的运行实例中,这些条件很可能都不成立。
相关文章:
- 检查输入 std::array 指针数据是否等于某个常量数组
- 指针数据类型变量如何包含对象?
- 如何在C++中使用类对象访问指针数据成员
- 如何强制实施有关指针数据成员的常量正确性
- 为什么指针>数据有效,而 *double_pointer->data 不起作用?
- 如何从C++中的原始指针数据构造张量流::张量
- 检查课程是否具有指针数据成员
- 处理类的指针数据成员的动态内存
- 在堆上启动的指针数据成员
- 具有指针数据类型的非类型函数模板参数
- 如何将复杂的指针数据作为属性放入qt-plugin-xml文件中
- C++指向函数作为参数的指针.数据类型不兼容
- 初始化指针数据结构的空间复杂性
- 运算符重载与 C++ : 具有指针数据成员的类
- 我是否需要清理非指针数据成员
- 在堆或堆栈上的指针类实例中分配C++非指针数据成员
- 函数结束后丢失指针数据
- C++ 如何确保复制构造函数不会修改原始对象的指针数据成员?
- 为什么从派生类访问基类的数据时会返回无意义的数据(我认为是指针数据)
- 将原始鼠标/指针数据转换为有意义的内容