Need of sizeof() in iostream::write()?

Need of sizeof() in iostream::write()?

本文关键字:write of iostream Need in sizeof      更新时间:2023-10-16

我认为标准库可以在如下代码中调用模板类型(no?)上的sizeof运算符:

#include <fstream>
int main()
{
    std::ofstream file("test.bin", std::ios::binary | std::ios::out);
    char buf = 42;
    file.write(&buf, sizeof(buf));
}

那么,有没有理由向程序员询问要在ostream::write()中写入的元素的大小?

PS:这是我的第一个问题,我不是英国人,请原谅

char *可能是

char const c = 'a';
char const * ptr = &c;        // char const *

与您的示例一样,但它也可以是字符串文字

std::string x("some string");
char const * ptr = x.c_str(); // also char const *!!

当你只有指针可用时,你如何决定你读取的内存地址?你需要一个长度:

file.write(x.c_str(), x.length());

您无法从指针中获取大小。ostream::写入

ostream& write (const char* s, streamsize n);

这里s只是指向一个位置,在这里使用sizeof不会让你知道你需要写多少字节,相反,它只会给你指针的大小。

如果不知道元素的数量,就无法找到指向数组的指针的大小。

Sizeof(ptr)返回平台指针的大小(8字节)或指向的结构的大小,具体取决于所使用的运算符。

char * ptr = "abcdef"
printf("%ld", sizeof(ptr));
printf("%ld", sizeof(*ptr));

第一个返回8(取决于平台),第二个返回1。即使通过"正确"的大小是6。

因此,为了知道缓冲区的大小,必须将大小作为附加参数传递。

出于同样的原因,memset和memcpy要求用户指定指针的大小。