gpt4 book ai didi

c++ - 是否需要在运算符(operator)身上丢弃垃圾?

转载 作者:行者123 更新时间:2023-12-01 15:12:28 25 4
gpt4 key购买 nike

运算符上是否需要[[nodiscard]]属性?还是可以安全地假设编译器将像对大多数可疑丢弃的东西一样发出警告?
例如。一种重载的operator+,应否应用该属性?特殊的运算符,例如函数强制转换运算符或新运算符呢?什么时候学究?

最佳答案

让我引用N.Josuttis的以下论文:“ [[nodiscard]] in the library”(有一些遗漏,请参见全文):

C++17 introduced the [[nodiscard]] attribute. The question is, where to apply it now in the standard library. It should be added where:

  • not using the return value always is a “huge mistake” (e.g. always resulting in resource leak),
  • not using the return value is a source of trouble and easily can happen (not obvious that something is wrong).

It should not be added when:

  • not using the return value is a possible/common way of programming at least for some input,
  • not using the return value makes no sense but doesn’t hurt and is usually not an error.

So, [[nodiscard]] should not signal bad code if this

  • can be useful not to use the return value,
  • is common not to use the return value,
  • doesn’t hurt and probably no state change was meant that doesn’t happen.

关于c++ - 是否需要在运算符(operator)身上丢弃垃圾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63203902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com