Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.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/C++风格--修改函数参数_C++_C_Coding Style_Pass By Value - Fatal编程技术网

C/C++风格--修改函数参数

C/C++风格--修改函数参数,c++,c,coding-style,pass-by-value,C++,C,Coding Style,Pass By Value,大家都知道C/C++函数参数是按值传递的。那么为什么有些人坚持正确的风格是在修改函数参数之前制作函数参数的本地副本呢?例如,他们会写: void baz(unsigned int *ptr) { unsigned int *lPtr = ptr; for(int i = 0; i < 10; i++) { foo(*lPtr++); } } 而不是: void baz(unsigned int *ptr) { for(int i = 0; i < 1

大家都知道C/C++函数参数是按值传递的。那么为什么有些人坚持正确的风格是在修改函数参数之前制作函数参数的本地副本呢?例如,他们会写:

void baz(unsigned int *ptr)
{
  unsigned int *lPtr = ptr;
  for(int i = 0; i < 10; i++)
  {
      foo(*lPtr++);
  }
}
而不是:

void baz(unsigned int *ptr)
{
  for(int i = 0; i < 10; i++)
  {
      foo(*ptr++);
  }
}

第二种方法似乎更容易阅读,因为它少了一个变量。

我认为这是因为代码的作者在baz的第一个版本中编写了变量声明,然后他重构了代码,将for循环中的代码移动到函数foo中,而作者错误地没有删除变量。变量是纯粹的浪费。希望这有帮助

唯一的理由是对于更大的函数,有人可能会在函数的底部添加新的功能,而没有意识到参数先前被修改或无效

想象一下:

int bighorriblefunction(const char * astr)
{
  // hundreds of lines of horribleness
  while ( * astr ) { /* something */  ++ astr ; }

  // more pages of code

  /** author two adds later */
  if ( ! strcmp(astr, "magicvalue") ) { /** do this really important thing **/  return 1 ; }
  return 0 ;
}

作者二号需要一段时间才能意识到新代码永远不会运行。

这是一个穷人版的接口与实现分离

假设您在一年前编写了此代码:

class Foo
{
public:
    void bar( const char *where )
    {
        // The dreaded copy
        const char *destination = where;

        // The actual implementation that in the real world may take 500 
        // lines of code with 20 references to the variable destination
    }
};
现在,一年后,您希望将参数where设置为可选,默认设置为类的成员变量。唉,你不记得那500行代码到底做了什么!幸运的是,使用前复制的参数保存了您的数据:

class Foo
{
public:
    void bar( const char *where = NULL)
    {
        // Hooray! I only have to change 1 line here!
        const char *destination = where? where : m_MyHomeDir.c_str();

        // The actual implementation that in the real world may take 500 
        // lines of code with 20 references to the variable destination
    }

private:
    std::string m_MyHomeDir;
};

如果你在C++中使用,只使用:

std::for_each(ptr, ptr+10, foo);

我知道,这并不能直接回答这个问题,但它确实指向了一个事实,即它通常应该是无关紧要的。如果它是相关的,你可能需要重写代码。

我不清楚这些人是谁,我从来没有听说过这个需求,但是我唯一能想到的正当理由是它稍微有助于调试:如果调试器在中间停止了函数,您可以看到它最初使用的参数值。但是,在大多数情况下,只需向上移动一个调用帧并查看传递给函数的表达式的值,就可以实现同样的效果。

他们这样做是因为原始值在调试时很有用。

我也不明白人们为什么这样做。也许来自C++的人习惯于偶然地传递和修改引用的风险…嗯,不太好。也许是为了在任何核心转储文件中都能很容易地看到函数参数的原始值?我真的不知道。这些人是谁?我同意你的看法。这里也是。。。然后我想不是每个人都是这样……我曾经看到过一个“学习C”课程的笔记,该课程教授一种高度公式化的方法,其中包括这类东西。我觉得这是在浪费空间。