从 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::vector
constructor is会很有用[[nodiscard]]
,这样上面的代码就会产生警告。
具有副作用的显着构造函数是unique_lock
锁构造函数,例如or lock_guard
。但是这些也是很好的标记目标[[nodiscard]]
,以避免错过范围,如下所示:
std::lock_guard{Mutex};
InterThreadVariable = value; // ouch, not protected by mutex
如果std::lock_guard
constructor is会很有用[[nodiscard]]
,这样上面的代码就会产生警告。
当然有这样的情况return std::lock_guard{Mutex}, InterThreadVariable;
。但是很少有[[nodiscard]]
守卫,并且像当地一样压制他们return ((void)std::lock_guard{Mutex}, InterThreadVariable);
那么,在任何情况下构造函数不应该被nodiscard?