F.17: For "in-out" parameters, pass by reference to non-const(输入/输出参数传递非常量引用)
译者注:in-out指的是向函数传递输入信息的同时又从函数获取输出信息的参数。
Reason(原因)
This makes it clear to callers that the object is assumed to be modified.
向调用者明示该对象可能被修改。
Example(示例)
void update(Record& r); // assume that update writes to r
Note(注意)
A T&
argument can pass information into a function as well as out of it. Thus T&
could be an in-out-parameter. That can in itself be a problem and a source of errors:
T&类型参数可以向函数传递信息也可以从函数获取信息。因此T&可以作为输入/输出参数使用。(但是如果运用不当,)它本身可能就是一个问题并且是错误的起因。
void f(string& s)
{
s = "New York"; // non-obvious error
}
void g()
{
string buffer = ".................................";
f(buffer);
// ...
}
Here, the writer of g()
is supplying a buffer for f()
to fill, but f()
simply replaces it (at a somewhat higher cost than a simple copy of the characters). A bad logic error can happen if the writer of g()
incorrectly assumes the size of the buffer
.
代码中函数g()的编写者向f()提供一个缓冲区用于填充,但是f()简单地替换了它(其代价稍高于简单的字符串拷贝)。如通过g()的编写者不正确地假设了buffer的大小,可能会导致非常不好的错误。
Enforcement(实施建议)
-
(Moderate) ((Foundation)) Warn about functions regarding reference to non-
const
parameters that do not write to them.(中等)((基本准则))当有函数将某引用视为非常量参数但又不去写它们的时候,报警。
译者注:如果只是用于输入信息,应该使用传值或者const类型。
-
(Simple) ((Foundation)) Warn when a non-
const
parameter being passed by reference ismove
d.(简单)((基本准则))当通过引用传递的非常量参数被移动的时候报警。
译者注:非常量参数意味着也会用于输出信息,如果内容被移动则无法继续使用。