C++核心准则边译边学-F.17 输入/输出参数传递非常量引用

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 is moved.

    (简单)((基本准则))当通过引用传递的非常量参数被移动的时候报警。

    译者注:非常量参数意味着也会用于输出信息,如果内容被移动则无法继续使用。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值