4

从 C++20 开始,[[nodiscard]]可以应用于构造函数。http://wg21.link/p1771有例子:

struct [[nodiscard]] my_scopeguard { /* ... */ };
struct my_unique {
  my_unique() = default;                                // does not acquire resource
  [[nodiscard]] my_unique(int fd) { /* ... */ }         // acquires resource
  ~my_unique() noexcept { /* ... */ }                   // releases resource, if any
  /* ... */
};
struct [[nodiscard]] error_info { /* ... */ };
error_info enable_missile_safety_mode();
void launch_missiles();
void test_missiles() {
  my_scopeguard();              // warning encouraged
  (void)my_scopeguard(),        // warning not encouraged, cast to void
    launch_missiles();          // comma operator, statement continues
  my_unique(42);                // warning encouraged
  my_unique();                  // warning not encouraged
  enable_missile_safety_mode(); // warning encouraged
  launch_missiles();
}
error_info &foo();
void f() { foo(); }             // warning not encouraged: not a nodiscard call, because neither
                                // the (reference) return type nor the function is declared nodiscard

通常构造函数没有副作用。所以丢弃结果是没有意义的。例如,std::vector如下丢弃是没有意义的:

std::vector{1,0,1,0,1,1,0,0};

如果std::vectorconstructor is会很有用[[nodiscard]],这样上面的代码就会产生警告。

具有副作用的显着构造函数unique_lock锁构造函数,例如or lock_guard。但是这些也是很好的标记目标[[nodiscard]],以避免错过范围,如下所示:

std::lock_guard{Mutex};
InterThreadVariable = value; // ouch, not protected by mutex

如果std::lock_guardconstructor is会很有用[[nodiscard]],这样上面的代码就会产生警告。

当然有这样的情况return std::lock_guard{Mutex}, InterThreadVariable;。但是很少有[[nodiscard]]守卫,并且像当地一样压制他们return ((void)std::lock_guard{Mutex}, InterThreadVariable);

那么,在任何情况下构造函数不应该nodiscard?

4

1 回答 1

3

库中的一个示例pybind11:要为 python 包装 C++ 类,您可以:

PYBIND11_MODULE(example, m) {
    py::class_<MyClass>(m, "MyClass");  // <-- discarded.
}
于 2021-09-19T11:29:00.170 回答