Ale*_*iev 6 c++ c++20 nodiscard
从 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
Run Code Online (Sandbox Code Playgroud)
通常构造函数没有副作用。所以丢弃结果是没有意义的。例如,std::vector如下丢弃是没有意义的:
std::vector{1,0,1,0,1,1,0,0};
Run Code Online (Sandbox Code Playgroud)
如果std::vector构造函数是[[nodiscard]],那么上面的代码会产生警告。
确实有副作用的值得注意的构造函数是锁构造函数,例如unique_lockor lock_guard。但这些也是标记的好目标[[nodiscard]],以避免错过范围,如下所示:
std::lock_guard{Mutex};
InterThreadVariable = value; // ouch, not protected by mutex
Run Code Online (Sandbox Code Playgroud)
如果std::lock_guard构造函数是[[nodiscard]],那么上面的代码会产生警告。
当然有这样的情况return std::lock_guard{Mutex}, InterThreadVariable;。但仍然有[[nodiscard]]守卫,并像这样在当地压制他们的情况已经很罕见了return ((void)std::lock_guard{Mutex}, InterThreadVariable);
那么,有没有什么情况下构造函数不应该被nodiscard 呢?
库中的一个示例pybind11:要为 python 包装 C++ 类,您需要执行以下操作:
PYBIND11_MODULE(example, m) {
py::class_<MyClass>(m, "MyClass"); // <-- discarded.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1414 次 |
| 最近记录: |