前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则编译边学-F.17 输入/输出参数传递非常量引用

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

作者头像
面向对象思考
发布2020-03-25 15:22:07
4180
发布2020-03-25 15:22:07
举报

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(示例)

代码语言:javascript
复制
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&可以作为输入/输出参数使用。(但是如果运用不当,)它本身可能就是一个问题并且是错误的起因。

代码语言:javascript
复制
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. (简单)((基本准则))当通过引用传递的非常量参数被移动的时候报警。 译者注:非常量参数意味着也会用于输出信息,如果内容被移动则无法继续使用。
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-11-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • F.17: For "in-out" parameters, pass by reference to non-const(输入/输出参数传递非常量引用)
    • Reason(原因)
      • Example(示例)
        • Note(注意)
          • Enforcement(实施建议)
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档