gpt4 book ai didi

c++ - 移动构造函数的意外调用

转载 作者:行者123 更新时间:2023-11-30 00:42:45 25 4
gpt4 key购买 nike

我正在用上面的代码练习 C++ 移动语义代码,但是 MemoryBlock 的值 25 的移动构造函数被调用了两次。之后,连续两次调用MemoryBlock的析构函数。

代码如下:

#include <iostream>
#include <vector>

class MemoryBlock {
private:
int length;
int* data;

public:
// Default constructor
MemoryBlock() = default;

// Constructor
explicit MemoryBlock(int p_length) : length(p_length), data(new int[length]) {
std::cout << "In MemoryBlock(int), length is " << length << ".\n";
}

// Destructor
~MemoryBlock() {
std::cout << "~MemoryBlock() is called. Deleting resources.\n";

delete[] data;
}

// Copy constructor
MemoryBlock(const MemoryBlock& other) : length(other.length), data(new int[other.length]) {
std::cout << "In MemoryBlock(const MemoryBlock&), length is " << length << ".\n";

for (int i = 0; i < length; ++i) {
data[i] = other.data[i];
}
}

// Move constructor
MemoryBlock(MemoryBlock&& other) noexcept : length(0), data(nullptr) {
std::cout << "In MemoryBlock(MemoryBlock&&), length is " << other.length << ".\n";

length = other.length;
data = other.data;

other.length = 0;
other.data = nullptr;
}
};

int main() {
std::vector<MemoryBlock> vec;

vec.push_back(MemoryBlock(25)); // (1)
vec.push_back(MemoryBlock(60)); // (2)

std::cout << "----------------- End of main() -----------------\n";

return 0;
}

(try it live)

结果:

In MemoryBlock(int), length is 25.            // #1: Generate temporary object
In MemoryBlock(MemoryBlock&&), length is 25. // Move temporary object #1 to vec's node
~MemoryBlock() is called. Deleting resources. // Destruct temporary object #1
In MemoryBlock(int), length is 60. // #2: Generate temporary object
In MemoryBlock(MemoryBlock&&), length is 60. // Move temporary object #2 to vec's node
In MemoryBlock(MemoryBlock&&), length is 25. // ??
~MemoryBlock() is called. Deleting resources. // ??
~MemoryBlock() is called. Deleting resources. // ??
----------------- End of main() -----------------
~MemoryBlock() is called. Deleting resources. // Destruct vec's node 60
~MemoryBlock() is called. Deleting resources. // Destruct vec's node 25

我想知道为什么调用标记为??的行。

最佳答案

您代码中的 Vector 最初容量为零。它的 Allocator 正在为位于 push_back 的一个对象分配内存。

vec.push_back(MemoryBlock(60)) 之后;//(2) 为 2 个元素分配了新的内存块,并将第一个元素移动到新的内存块。

使用 vec.reserve(2); 来避免这种情况。

关于c++ - 移动构造函数的意外调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58427291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com