gpt4 book ai didi

c++ - istream_iterator 不进行零初始化

转载 作者:搜寻专家 更新时间:2023-10-31 01:35:17 26 4
gpt4 key购买 nike

这是一个 Minimal, Complete, Verifiable Example我知道这不是copacetic。无论如何,给定结构:

struct Foo {
int even;
int odd;
};

istream& operator>>(istream& lhs, Foo& rhs) {
int input;

lhs >> input;

(input % 2 == 0 ? rhs.even : rhs.odd) = input;

return lhs;
}

我可以做以下事情:

stringstream bar("1 2 3 4 5 6 7 8 9 0");

for (const auto& i : vector<Foo>{istream_iterator<Foo>(bar), istream_iterator<Foo>()}) {
cout << i.even << ' ' << i.odd << endl;
}

但是这给了我结果:

-1215720516 1
2 1
2 3
4 3
4 5
6 5
6 7
8 7
8 9
0 9

要对 Foo 进行零初始化,我可以编写代码:

for(Foo i{}; bar >> i; i = Foo{}) {
cout << i.even << ' ' << i.odd << endl;
}

这给出了我预期的结果:

0 1
2 0
0 3
4 0
0 5
6 0
0 7
8 0
0 9
0 0

我知道使用不完全覆盖变量的提取运算符是粗略的。这最初源于我的回答 here我的问题 here在我看来,它更自然地期望对读取之间的变量进行零初始化。在任何情况下,是否可以使用 istream_iterator 使变量在读取之间被零初始化,或者我必须使用 for 循环?

最佳答案

in my mind had a more natural expectation of zero-initializing the variable in-between reads

这是不正确的期望。 operator>> 应该完全并且单独负责初始化对象。您不能假设该对象之前已被默认/值初始化。一个非常标准的用例是在 while 循环中读取所有对象:

Foo foo;
while (std::cin >> foo) { ... }

第二次,foo 将具有旧值 - 这里没有任何归零。因此,您需要确保当您的运算符(operator)返回时,新对象已完全由您设置。

最简单的事情是先对其进行值初始化:

istream& operator>>(istream& lhs, Foo& rhs) {
int input;
lhs >> input;
rhs = Foo{}; // <== add this
input % 2 == 0 ? rhs.even : rhs.odd) = input;
return lhs;
}

或者,您可以手动编写两者:

if (input % 2 == 0) {
rhs.odd = 0;
rhs.even = input;
}
else {
rhs.odd = input;
rhs.even = 0;
}

或聚合初始化每个案例:

rhs = input % 2 == 0 ? Foo{input, 0} : Foo{0, input};

无论如何,operator>> 负责将您想要清零的值清零。

关于c++ - istream_iterator 不进行零初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37682156/

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