gpt4 book ai didi

c++ - 为什么将字符串输出到未命名的 std::ofstream 却给我一个十六进制数?

转载 作者:太空狗 更新时间:2023-10-29 20:02:12 28 4
gpt4 key购买 nike

我试图将一些调试输出添加到 C++03 项目中,但得到了一些奇怪的结果。这是简化的测试代码:

#include <fstream>

int main()
{
{
std::ofstream file("/tmp/test.txt");
file << "hello" << " ... OK, this works\n";
}
std::ofstream("/tmp/test.txt",std::ios_base::app) << "hello"
<< " ... no, I mean hello!\n";
}

出于某种原因,这是我在编译后得到的:

$ g++ test.cpp -o test && ./test && cat /tmp/test.txt
hello ... OK, this works
0x80487fe ... no, I mean hello!

为什么在将字符串输出到未命名的 std::ofstream 对象时得到一个十六进制数?为什么第二个字符串的后续输出有效?

最佳答案

通常operator<<我们用它来将 C 字符串传递给 std::ostreamdeclared as一个免费的功能

template< class Traits >
basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os,
const char* s );

无名std::ofstream object 是一个临时变量,临时变量不能绑定(bind)到非常量引用,因此这个运算符重载不参与重载决议。相反,取最接近的匹配,一个成员函数

std::basic_ostream& std::basic_ostream::operator<<(const void*);

,它接受一个类型删除的指针并只打印它的值。由于可以使用临时对象调用成员函数,所以这个确实可行。这解释了输出中的十六进制数。现在,这个运算符返回一个引用,std::basic_ostream& .由于这不再是一个临时对象,而是对某个非常量对象的引用,通常的自由函数重载 operator<< ,这需要 const char* , 可以调用成功。这就是第二个字符串按预期打印的原因。

请注意,自 C++11 起,代码将按预期工作,因为我们有一个额外的重载 operator<< ,它采用右值引用:

template< class CharT, class Traits, class T >
basic_ostream< CharT, Traits >& operator<<( basic_ostream<CharT,Traits>&& os,
const T& value );

,并且临时对象确实绑定(bind)到右值引用。

要使代码在 C++03 中工作,您可以使用成员函数 std::ostream::flush() ,它返回对该对象的非常量引用并且对 fstream 没有任何用户可见的副作用对象:

#include <fstream>

int main()
{
std::ofstream("/tmp/test.txt").flush() << "hello"
<< " ... OK, this now works too\n";
}

关于c++ - 为什么将字符串输出到未命名的 std::ofstream 却给我一个十六进制数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45085960/

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