Need of sizeof() in iostream::write()?
Need of sizeof() in iostream::write()?
我认为标准库可以在如下代码中调用模板类型(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要求用户指定指针的大小。
相关文章:
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- 赛通"Cannot take address of memoryview slice"
- C++ Version Of Double.longBitsToDouble
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ Usage of AsyncCallback
- 错误:"Left of getValue must have class/struct/union"
- 瓦尔格林德:在字符[]到标准::向量迁移之后"Invalid write of size 1"<char>
- 瓦尔格林德给出"Invalid write of size 8"空析构函数
- Need of sizeof() in iostream::write()?
- 瓦尔格林德"Invalid write of size 8"