函数声明和定义中使用noexcept指定符的作用是什么?

19

请考虑以下函数:

// Declaration in the .h file
class MyClass
{
    template <class T> void function(T&& x) const;
};

// Definition in the .cpp file
template <class T> void MyClass::function(T&& x) const;

如果类型 T 具有不抛出异常的构造函数,我希望将此函数设置为 noexcept

如何实现?(我的意思是语法是什么?)


2
你可以使用 std::is_nothrow_constructible 进行检查。 - Jarod42
我知道但我以前从未使用过noexcept关键字,所以我想知道它的语法是什么。 - Vincent
nothrow构造函数需要哪些参数?答案假设您指的是像T foo;这样的nothrow 默认构造函数,但由于函数采用通用引用,我想知道您是否指的是从函数参数中nothrow构造函数,例如T foo{std::forward<T>(x)}; - Casey
2个回答

23

就像这样:

#include <type_traits>

// Declaration in the .h file
class MyClass
{
    public:
    template <class T> void function(T&& x) noexcept(std::is_nothrow_constructible<T>::value);
};

// Definition in the .cpp file
template <class T> void MyClass::function(T&& x) noexcept(std::is_nothrow_constructible<T>::value);

实例演示

但请也看看为什么模板只能在头文件中实现?通常情况下,不能在源文件中实现模板。


7

noexcept 可以接受一个表达式,如果表达式的值为真,则声明该函数不会抛出任何异常。因此语法如下:

class MyClass
{
template <class T> void function(T&& x) noexcept (noexcept(T()));
};

// Definition in the .cpp file
template <class T> void MyClass::function(T&& x) noexcept (noexcept(T()))
{

}

编辑:在这种情况下,使用如下所示的std::is_nothrow_constructible<T>::value会更加简洁。


从技术上讲,noexcept(noexcept(T()))并不意味着可以在不发生异常的情况下构造T;它意味着可以在不发生异常的情况下构造和销毁T。你需要使用noexcept(noexcept(::new (nullptr) T())) - Zizheng Tai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接