Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ iostream::write()中是否需要sizeof()?_C++_Sizeof_Ostream - Fatal编程技术网

C++ iostream::write()中是否需要sizeof()?

C++ iostream::write()中是否需要sizeof()?,c++,sizeof,ostream,C++,Sizeof,Ostream,我认为标准库可以在这样的代码中对模板类型(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)); } #包括 int main() { 流文件的std::of(“test.bin”,s

我认为标准库可以在这样的代码中对模板类型(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));
}
#包括
int main()
{
流文件的std::of(“test.bin”,std::ios::binary | std::ios::out);
char-buf=42;
write(&buf,sizeof(buf));
}
那么,有没有理由要求程序员输入要在ostream::write()中写入的元素的大小


附:这是我的第一个问题,我不是英国人,请宽容一点。

你不能从指针上得到大小

ostream&write(常量字符*s,流大小n)


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

您无法从指针获取大小

ostream&write(常量字符*s,流大小n)


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

a
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());

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());

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

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

char * ptr = "abcdef"

printf("%ld", sizeof(ptr));
printf("%ld", sizeof(*ptr));
第一个返回8(取决于平台),第二个返回1。即使“正确”尺寸为6

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


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

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

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

char * ptr = "abcdef"

printf("%ld", sizeof(ptr));
printf("%ld", sizeof(*ptr));
第一个返回8(取决于平台),第二个返回1。即使“正确”尺寸为6

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


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

ostream::write
不是模板。它只接受
char*
。因为
write
接受一个指针,第二个参数表示要写入多少元素。@BenjaminLindley:在我阅读问题时,不是关于实际签名,而是关于基本原理。为什么它不是模板?
ostream::write
不是模板。它只接受
char*
。因为
write
接受一个指针,第二个参数表示要写入多少元素。@BenjaminLindley:在我阅读问题时,不是关于实际签名,而是关于基本原理。为什么它不是一个模板?