gpt4 book ai didi

c++ - 不变问题和隐式 move 构造函数

转载 作者:行者123 更新时间:2023-11-28 00:56:44 24 4
gpt4 key购买 nike

我读了这篇文章cppnext implicit move但我不明白这个问题:

#include <iostream>
#include <vector>
struct X
{
// invariant: v.size() == 5
X() : v(5) {}

~X()
{
std::cout << v[0] << std::endl;
}

private:
std::vector<int> v;
};

int main()
{
std::vector<X> y;
y.push_back(X()); // X() rvalue: copied in C++03, moved in C++0x
}

在 MSVC2010 下运行时没有错误...谁能帮帮我?

这篇文章中有这样一句话:

The key problem here is that in C++03, X had an invariant that its v member always had 5 elements. X::~X() counted on that invariant, but the newly-introduced move constructor moved from v, thereby setting its length to zero.

我不明白为什么因为我们尝试 move X,v 长度将为零

最佳答案

文章试图说明的问题是,当 X 在 push_back 中 move 时,不变量被破坏。临时 X 的 vector v move 后将为空,因此析构函数调用将调用未定义的行为。 您可能没有发现任何问题,因为您的编译器没有实现 move 语义,或者因为未定义的行为纯属偶然,不会导致任何可察觉的运行时错误。

你可以用这个简单的程序来检查这个行为,我们明确地 move 了一个 X 实例:

#include <vector>
#include <iostream>
struct X {
X() : v(5) {}
std::vector<int> v;
};

int main() {
X x0;
std::cout << x0.v.size() << ", ";
X x1 = std::move(x0);
std::cout << x0.v.size() << "\n";
}

在 GCC 4.7 上,这些产生

5, 0

这来自 std::vector 的 move 构造函数,它被 X 的隐式生成的构造函数使用。您可以直接检查 std::vector:

int main() {
std::vector<int> v0(5);
std::cout << v0.size() << ", ";
std::vector<int> v1 = std::move(v0);
std::cout << v0.size() << "\n";
}

这会产生相同的输出。

现在,在您引用的示例中,用户定义的析构函数 的存在意味着没有隐式生成的 move 构造函数,因此 X 不是push_back 中 move 。

关于c++ - 不变问题和隐式 move 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10796910/

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