std::vector 使用 {} 赋值的问题
std::vector 使用 {} 赋值的问题
结论 1:operator=(vector&&) 会析构原 vector。
结论 2:operator=(const vector&) 和 operator=(std::initializer_list<T>) 不会释放原 vector 内存。
可以通过观察赋值后的 vector 的 capacity 证明。
结论 3:vec = {} 不会释放 vec 的内存。
因为这时调用了 operator=(std::initializer_list<T>)。
结论 4:vec = vector<int>() 或 vector<int>.swap(vec) 可以释放 vec 的内存。
因为这时调用的都是 operator=(vector&&)。
结论 5:exchange(vec, {}) 会释放 vec 的内存。
此时将 {} 转型为了 vector<int>,从而调用了 operator=(vector&&)。以下是代码的证明:
#include <iostream>
#include <bits/stdc++.h>
#include <initializer_list>
template<typename T>
class vector {
public:
// 默认构造函数
vector() {
std::cout << "vector()" << std::endl;
}
// 拷贝构造函数
vector(const vector& other) {
std::cout << "vector( const vector& other )" << std::endl;
}
// 移动构造函数
vector(vector&& other) {
std::cout << "vector( vector&& other )" << std::endl;
}
// 初始化列表构造函数
vector(std::initializer_list<T> init) {
std::cout << "vector( std::initializer_list<T> init)" << std::endl;
}
// 拷贝赋值运算符
vector& operator=(const vector& other) {
std::cout << "vector& operator=( const vector& other )" << std::endl;
return *this;
}
// 移动赋值运算符
vector& operator=(vector&& other) {
std::cout << "vector& operator=( vector&& other )" << std::endl;
return *this;
}
// 初始化列表赋值运算符
vector& operator=(std::initializer_list<T> ilist) {
std::cout << "vector& operator=( std::initializer_list<T> ilist )" << std::endl;
return *this;
}
};
int main() {
// vector<int> v1;
// vector<int> v2(v1);
// vector<int> v3(std::move(v2));
// vector<int> v4 = {1, 2, 3};
// v1 = v4;
// v1 = std::move(v4);
// v1 = {4, 5, 6};
vector<int> v1{1, 2, 3};
std::cout << __LINE__ << std::endl;
std::exchange(v1, {});
return 0;
}
输出为
vector( std::initializer_list<T> init)
56
vector()
vector( vector&& other )
vector& operator=( vector&& other )
证明它使用了移动构造函数,那么一定会释放内存。或者也可以观察 capacity 得到这个结论。
本文来自博客园,作者:caijianhong,转载请注明原文链接:https://www.cnblogs.com/caijianhong/p/18806076
浙公网安备 33010602011771号