为什么std :: hex导致内存腐败vector.size()



我有以下代码:

vector<UINT_PTR> test = GetMemoryAddresses();
cout << "Size: " << test.size() << endl;
for (UINT_PTR a : test) {
    cout << "Memory Address: " << hex  << a << endl;
}
cout << "Size: " << test.size() << endl;

哪些打印以下结果:

Size: 18
Memory Address: fc06a0
Memory Address: 13a70f0
Memory Address: 36c78c1
Memory Address: 3da0ea0
Memory Address: 3e21b80
Memory Address: c0a6881
Memory Address: c747690
Memory Address: c748b98
Memory Address: c74a1b8
Memory Address: c74ce10
Memory Address: c750c78
Memory Address: 1340a10f
Memory Address: 14376ea0
Memory Address: 14472649
Memory Address: 69867268
Memory Address: 6bdf9243
Memory Address: 7399a142
Memory Address: 76c54875
Size: 12

删除

&lt;&lt;十六进制

再次导致正确的vector.size()再次。

是什么引起了这种记忆核的?

我做错了吗?

std::hex是"粘性"。它将流的状态设置为十六进制的显示,这就是它将留在那里直到更改它的地方。这意味着当您这样做

cout << "Size: " << test.size() << endl;

您在十六进制中显示大小,十进制为12个十六进制。

您需要

cout << "Size: " << dec << test.size() << endl;

切换回小数模式并显示"正确"的大小。


另一件事可以帮助您诊断出这种情况,就是使用std::showbase。这是另一个"粘性"操纵器,将使用0x预先预先六核输出。在

中使用
cout << "Memory Address: " << hex << showbase  << a << endl;

会使您的输出

Size: 18
Memory Address: 0xfc06a0
Memory Address: 0x13a70f0
Memory Address: 0x36c78c1
Memory Address: 0x3da0ea0
Memory Address: 0x3e21b80
Memory Address: 0xc0a6881
Memory Address: 0xc747690
Memory Address: 0xc748b98
Memory Address: 0xc74a1b8
Memory Address: 0xc74ce10
Memory Address: 0xc750c78
Memory Address: 0x1340a10f
Memory Address: 0x14376ea0
Memory Address: 0x14472649
Memory Address: 0x69867268
Memory Address: 0x6bdf9243
Memory Address: 0x7399a142
Memory Address: 0x76c54875
Size: 0x12

这使得更清楚的是,对cout的最后一个电话仍在使用hex

std::cout << std::hex;

使std::cout打印的所有数字作为十六进制。要再次运行十进制:

std::cout << std::dec;

理想情况下,在使用任何流格式操纵器(如std::hex)之前,您应该保存格式标志并在完成时还原它们。例如:

auto flags = std::cout.flags();
std::cout << std::hex << 10 << "n";
std::cout.flags( flags );

所有标志都需要像这样重置:https://en.cppreference.com/w/cpp/io/ios_base/flags

填充字符也很粘:https://en.cppreference.com/w/cpp/io/basic_ios/fill,精度也是如此:https://en.cppreference.com/w/cpp/io/ios_base/precision

唯一不是宽度标志的

:https://en.cppreference.com/w/cpp/io/ios_base/width

boost有一个实用程序类,将所有流状态重置回初始值:https://www.boost.org/doc/libs/1_69_0/libs/io/io/doc/doc/ios_state.html

相关内容

  • 没有找到相关文章

最新更新