是什么解释了这个片段中如此多的移动和破坏

What explains so many moves and destructions in this snippet

本文关键字:移动 解释 片段 是什么      更新时间:2023-10-16

为了理解五法则,我想出了这个:

#include <iostream>
#include <vector>
class A
{
public:
A(int y)
{
std::cout << "constructedn";
x = new int[y];
}
~A()
{
std::cout << "destructedn";
delete[] x;
}
A(const A &other)
{
std::cout << "copiedn";
if (other.x != nullptr)
x = new int[sizeof(other.x) / sizeof(other.x[0])];
}
A(A && other) :
x(other.x)
{
std::cout << "movedn";
other.x = nullptr;
}
A& operator=(A other)
{
std::cout << "assignmentsn";
std::swap(x, other.x);
return *this;
}
int *x;
};
class B
{
private:
std::vector<A> a;
public:
B()
{
for (int i = 0; i < 5; i++)
a.emplace_back(A(1));
std::cout << "----------------------n";
for (int i = 0; i < 5; i++)
a.push_back({ 2 });
}
};
int main()
{
B *b = new B();
std::cin.get();
}

相反,如果我分别使用 emplace_back 和 push_back 1 次,无论我调用每个方法的顺序如何,我都会得到以下输出:

constructed
moved
destructed
----------------------
constructed
moved
destructed
moved
destructed

我接受这一点。但是,如果我使用上面写的代码,我会得到一些棘手的模式:

constructed
moved
destructed
constructed
moved
destructed
moved
destructed
constructed
moved
moved
destructed
destructed
moved
destructed
constructed
moved
moved
moved
destructed
destructed
destructed
moved
destructed
constructed
moved
moved
moved
moved
destructed
destructed
destructed
destructed
moved
destructed
----------------------
constructed
moved
destructed
constructed
moved
moved
moved
moved
moved
moved
destructed
destructed
destructed
destructed
destructed
destructed
moved
destructed
constructed
moved
destructed
constructed
moved
destructed
constructed
moved
moved
moved
moved
moved
moved
moved
moved
moved
destructed
destructed
destructed
destructed
destructed
destructed
destructed
destructed
destructed
moved
destructed

是什么解释了这么多"移动"和"破坏"?另外,我们是否可以说emplace_back比仅通过此输出push_back更好?

我认为此输出不是错误

如果 std::vector 的大小已满并且您尝试推送,Vector 将分配更多内存并将原始内存块中的对象移动到新的内存块并销毁原始内存块。

所以 您可以使用 std::vector.reserve((

#include <iostream>
#include <vector>
class A
{
public:
A(int y)
{
std::cout << "constructedn";
x = new int[y];
}
~A()
{
std::cout << "destructedn";
delete[] x;
}
A(const A &other)
{
std::cout << "copiedn";
if (other.x != nullptr)
x = new int[sizeof(other.x) / sizeof(other.x[0])];
}
A(A && other) :
x(other.x)
{
std::cout << "movedn";
other.x = nullptr;
}
A& operator=(A other)
{
std::cout << "assignmentsn";
std::swap(x, other.x);
return *this;
}
int *x;
};
class B
{
private:
std::vector<A> a;
public:
B()
{
//reserve
a.reserve(5);
for (int i = 0; i < 5; i++)
a.emplace_back(A(1));
std::cout << "----------------------n";
// for (int i = 0; i < 5; i++)
//    a.push_back({ 2 });
}
};
int main()
{
B *b = new B();
std::cin.get();
}

此输出将如下所示

constructed
moved
destructed
constructed
moved
destructed
constructed
moved
destructed
constructed
moved
destructed
constructed
moved
destructed