我正在检查班级setg()
中的函数std::basic_streambuf
。它在文件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.
我理解由于成员变量是非const char_type*
,因此函数setg()
只能接受非const参数。
但是这些指针的目的是检索事物,那些指针char_type *
首先应该被声明为const char_type*
,对吧?
因为成员变量指针是非常量指针,我会假设在某些特定情况下可以更改指针指向的值。
我的问题是basic_streambuf
对象在什么情况下会改变get区域中的值?如果获取区域内容不会被更改,是否有充分的理由不应使用常量指针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)
关于这个问题的一些背景故事。我的同事修改了一个调用foo()
的函数setg()
,因此输入参数是非常量的。但不应修改foo()
的输入参数。由于参数setg()
是非常量的。 foo()
的函数参数不能是常量。通过他的单元测试案例的修改但由于修改导致的失败改变了输入值。如果setg()
首先采用const,则世界会更好
编辑结束1
PS当我再次阅读该函数时,变量名称给我留下了深刻印象,函数setg()
的第二个参数命名为_gnext
,它被分配给名为_M_in_cur
的指针,我几乎修改了我的代码,在指针进入函数之前将其递增为1。干得好的无论谁命名参数。
提前感谢您提供的任何解释
r0nG
答案 0 :(得分:1)
get区域是用于从关联的输入序列中读取字符的缓冲区。如果调用了read方法但get区域中没有足够的字符,basic_streambuf
对象将读取相关的输入序列以更新get区域中的内容。在这种情况下,get区域中的内容将被修改。