gpt4 book ai didi

c++ - 为什么函数 std::basic_streambuf::seth() 采用非常量参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:07:18 24 4
gpt4 key购买 nike

我正在检查 std::basic_streambuf 类中的函数 setg()。它在文件 streambuf 中定义。

gcc版本是5.4.0

我使用的编译选项是-std=gnu++14

void
setg(char_type* __gbeg, char_type* __gnext, char_type* __gend)
{
_M_in_beg = __gbeg;
_M_in_cur = __gnext;
_M_in_end = __gend;
}

成员变量声明为:

char_type*      _M_in_beg;     ///< Start of get area.
char_type* _M_in_cur; ///< Current read area.
char_type* _M_in_end; ///< End of get area.
char_type* _M_out_beg; ///< Start of put area.
char_type* _M_out_cur; ///< Current put area.
char_type* _M_out_end; ///< End of put area.

据我所知,由于成员变量是非常量 char_type*,函数 setg() 只能接受非常量参数。但是那些指针的目的是检索东西,那些指针 char_type * 应该首先声明为 const char_type* ,对吧?

因为成员变量指针是非常量指针,我假设这些指针指向的值在某些特定情况下可以更改。

我的问题是basic_streambuf对象在什么情况下会改变get区的值?如果获取区域内容不会改变,是否有充分的理由不使用 const 指针 cosnt char_type*

编辑 1
在这种情况下,成员变量可以声明为:

char_type const *_M_in_beg;     ///< Start of get area.
char_type const *_M_in_cur; ///< Current read area.
char_type const *_M_in_end; ///< End of get area.
char_type *_M_out_beg; ///< Start of put area.
char_type *_M_out_cur; ///< Current put area.
char_type *_M_out_end; ///< End of put area.

所以 setg() 可以声明为:

void
setg(char_type const* __gbeg, char_type const* __gnext, char_type const* __gend)

关于这个问题的一些背景故事。我的同事修改了一个调用 setg() 的函数 foo(),因此输入参数是非常量。但是 foo() 的输入参数不应该被修改。由于参数 setg() 是非常量。 foo() 的函数参数不能是常量。修改通过了他的单元测试用例,但由于修改更改了输入值而导致我的失败。如果 setg() 首先采用 const,那么世界会更美好。
编辑 1 结束

PS 当我再次阅读函数时,变量名给我留下了深刻的印象,函数 setg() 的第二个参数命名为 _gnext 并将其分配给名为_M_in_cur,我几乎修改了我的代码以在指针传递给函数之前将其递增到 1。为参数命名的人干得好。

basic_streambuf reference

预先感谢您提供的任何解释

r0nG

最佳答案

获取区是一个缓冲区,用于从关联的输入序列中读取字符。如果调用了读取方法,但获取区域中没有足够的字符,basic_streambuf 对象将读取关联的输入序列以更新获取区域中的内容。此时,修改了get区中的内容。

关于c++ - 为什么函数 std::basic_streambuf::seth() 采用非常量参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47805735/

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