Google关于将输入/输出参数作为指针的样式指南 [英] Google's style guide about input/output parameters as pointers

查看:166
本文介绍了Google关于将输入/输出参数作为指针的样式指南的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Google C ++样式指南做出了明显的区分(严格遵循通过 cpplint.py )在输入参数(→const ref,值)和输入输出或输出参数(→非const指针):

The Google C++ Style Guide draws a clear distinction (strictly followed by cpplint.py) between input parameters(→ const ref, value) and input-output or output parameters (→ non const pointers) :

C/C ++函数的参数要么输入到函数,要么输出 从功能或两者兼而有之.输入参数通常是值或 const引用,而输出和输入/输出参数将是 非常量指针.

Parameters to C/C++ functions are either input to the function, output from the function, or both. Input parameters are usually values or const references, while output and input/output parameters will be non-const pointers.

进一步:

实际上,在Google代码中有一个非常强的约定,输入参数是值或const引用,而输出参数是指针.

In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers.

但是我无法弄清楚为什么不应通过引用传递输入/输出参数(我将输出参数放在一边).在stackoverflow上有很多与此问题相关的主题: 此处,接受的答案清楚地表明:

But I can't figure out why input/output arguments (I leave output arguments aside) should not be passed by reference. On stackoverflow there are plenty of topics related to this question : e.g. here, the accepted answer clearly say that

主要与风格有关

it's mostly about style

但是如果

您希望能够传递null,必须使用指针

you want to be able to pass null, you must use a pointer

那么,如果我想避免指针为null,那么总是又有什么意义呢?为什么只对输入参数使用引用?

So, what's the point to always demand a pointer if I want to avoid the pointer to be null ? Why only use references for input arguments ?

推荐答案

要求将输出参数作为指针传递的原因很简单:

The reason for demanding that output parameters are passed as pointers is simple:

在呼叫站点上清楚地显示 ,该参数可能会发生突变:

It makes it clear at the call site that the argument is potentially going to be mutated:

foo(x, y);     // x and y won't be mutated
bar(x, &y);    // y may be mutated

当代码库不断发展并经历增量更改,这些更改可能一直由不了解整个上下文的人员审阅时,重要的是能够尽快了解更改的上下文和影响.因此,使用此样式规则,可以立即清楚地知道更改是否引入了突变.

When a code base evolves and undergoes incremental changes that are reviewed by people who may not know the entire context all the time, it is important to be able to understand the context and impact of a change as quickly as possible. So with this style rule, it is immediately clear whether a change introduces a mutation.

这篇关于Google关于将输入/输出参数作为指针的样式指南的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆