假设您有以下代码:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> First{"example", "second" , "C++" , "Hello world" };
std::vector<std::string> Second{"Hello"};
First.swap(Second);
for(auto a : Second) std::cout << a << "\n";
return 0;
}
假设向量不是std::string
,而是类:
std::vector<Widget> WidgetVector;
std::vector<Widget2> Widget2Vector;
用std::vector::swap
方法交换这两个向量仍然安全吗:WidgetVector.swap(Widget2Vector);
还是会导致UB?
发布于 2019-12-21 22:44:28
using std::swap; swap(a, b);
和a.swap(b);
的语义与后者完全相同,至少对于任何正常的类型都是如此。在这方面,所有标准类型都是正常的。
除非您使用有趣的分配器(意思是有状态的,不总是相等的,并且没有在容器交换上传播,请参阅std::allocator_traits
),否则使用相同的模板交换两个std::vector
-参数只是三个值(容量、大小和数据指针)的无聊交换。并且交换基本类型,没有数据竞争,是安全的,不能抛出。
标准甚至保证了这一点。见std::vector::swap()
。
https://stackoverflow.com/questions/59428993
复制相似问题