如果mystruct中的 data是 vector而不是指针呢, 哪个开销更大
时间: 2024-03-27 16:36:51 浏览: 18
如果 `MyStruct` 中的 `data` 是 `vector` 类型而不是指针类型,使用移动语义的开销仍然比使用拷贝构造函数的开销要小。这是因为 `vector` 类型已经实现了移动构造函数和移动赋值运算符,可以直接将原对象中的内存空间移动到新对象中,而不需要进行分配和复制操作。
下面是一个使用 `vector` 类型的例子,可以看到使用移动语义的开销仍然比使用拷贝构造函数的开销要小:
```cpp
#include <iostream>
#include <vector>
#include <chrono>
using namespace std;
using namespace std::chrono;
struct MyStruct {
int id;
double score;
vector<int> data;
MyStruct() : id(0), score(0.0), data{} {}
MyStruct(const MyStruct& other) : id(other.id), score(other.score), data(other.data) {}
MyStruct& operator=(const MyStruct& other) {
if (this != &other) {
id = other.id;
score = other.score;
data = other.data;
}
return *this;
}
MyStruct(MyStruct&& other) : id(other.id), score(other.score), data(move(other.data)) {}
MyStruct& operator=(MyStruct&& other) {
if (this != &other) {
id = other.id;
score = other.score;
data = move(other.data);
}
return *this;
}
};
int main() {
MyStruct a{1, 90.5, {1,2,3,4,5}};
auto start1 = high_resolution_clock::now();
MyStruct b = move(a); // 使用移动构造函数
auto end1 = high_resolution_clock::now();
auto duration1 = duration_cast<microseconds>(end1 - start1);
cout << "使用移动构造函数的时间:" << duration1.count() << " 微秒" << endl;
MyStruct c{2, 85.5, {6,7,8,9,10}};
auto start2 = high_resolution_clock::now();
MyStruct d = c; // 使用拷贝构造函数
auto end2 = high_resolution_clock::now();
auto duration2 = duration_cast<microseconds>(end2 - start2);
cout << "使用拷贝构造函数的时间:" << duration2.count() << " 微秒" << endl;
return 0;
}
```
在上面的例子中,我们使用 `vector` 类型替换了 `MyStruct` 中的指针成员变量 `data`,并且重载了拷贝构造函数、赋值运算符函数和移动构造函数、移动赋值运算符函数。在进行移动操作时,我们直接使用 `move` 函数将原对象中的 `vector` 移动到新对象中,而不需要重新分配和复制内存。可以看到,使用移动构造函数的开销仍然比使用拷贝构造函数的开销要小。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)