匿名std :: ofstream错误地处理字符数组

Rod*_*iro 6 c++ stl

以下代码将字符串文字输出到具有匿名和命名流的文件:

#include <fstream>

using namespace std;

int main()
{
    ofstream("testfile") << "test" << endl;

    ofstream ofs ("testfile2");
    ofs << "test2" << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

从strace的输出中可以看到,只有命名的流工作:

open("testfile", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
write(3, "0x400a91\n", 9)               = 9
close(3)                                = 0
open("testfile2", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
write(3, "test2\n", 6)                  = 6
close(3)                                = 0
Run Code Online (Sandbox Code Playgroud)

此外,如果您使用std :: string而不是文字,则无法编译.

为什么是这样?

Bo *_*son 9

您有一个问题,"匿名流"是一个右值,而使用C++ 98,您只能在其上调用成员函数.该stream << "test"会结合服用成员void*输出指针的地址.

C++ 11添加了operator<<一个rvalue流,这将使代码工作.


eca*_*mur 4

在C++03中,输出字符指针和字符串的非成员运算符不能用右值调用,因为它们需要左值引用,因此operator<<(const void *)调用成员。在 C++11 中,这是通过编写采用右值引用的重载来解决的,但在 C++03 中,您可以通过调用返回左值引用的成员函数或成员运算符来解决此问题(请注意,非常量成员函数可以在右值上调用):

ofstream("testfile").write("", 0) << "test" << endl;
Run Code Online (Sandbox Code Playgroud)

您可以轻松编写一个操纵器来执行此操作:

std::ios_base& (*do_nothing)(std::ios_base&) ) {}

ofstream("testfile") << do_nothing << "test" << endl;
Run Code Online (Sandbox Code Playgroud)