// 示例代码:使用 noexcept 指定函数不会抛出异常
#include <iostream>
#include <vector>
class Example {
public:
// 构造函数不会抛出异常
Example() noexcept {}
// move 构造函数不会抛出异常
Example(Example&& other) noexcept : data(other.data) {
other.data = nullptr;
}
// 一个可能抛出异常的函数,但在这里我们用 noexcept 表示它不会抛出异常
void doSomething() noexcept {
// 假设这里有一些操作,但我们确保它们不会抛出异常
std::cout << "Doing something without throwing exceptions." << std::endl;
}
private:
int* data;
};
int main() {
Example e1;
Example e2 = std::move(e1); // 使用 move 构造函数
e2.doSomething(); // 调用不会抛出异常的成员函数
return 0;
}
noexcept
是 C++11 引入的关键字,用于指定函数不会抛出异常。noexcept
可以提高性能,因为编译器可以优化这些函数的调用。noexcept
的函数中抛出了异常,程序会调用 std::terminate
终止执行。因此,使用 noexcept
时要确保函数确实不会抛出异常。Example
类的构造函数、移动构造函数和 doSomething
成员函数都被标记为 noexcept
,表示它们不会抛出任何异常。上一篇:c++ extern关键字
下一篇:c++游戏编程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站