我目前正在阅读一本C ++书籍,遇到了我不知道如何解释的这段代码:
#include <exception>
#include <memory>
struct empty_stack: std::exception // don't know what the code after : means
{
const char* what() const throw(); //don't understand this line either
};
答案 0 :(得分:4)
struct empty_stack: std::exception // don't know what the code after : means
这意味着empty_stack
从std::exception
公开继承,private
是标准异常的基类。
注意:如果未指定继承类型,则默认的继承类型取决于继承类型。如果继承类型为class
,则为public
;如果继承类型为struct
,则为const char* what() const throw(); //don't understand this line either
。
what()
这意味着throw()
是一个不会修改其所属类的非可变成员的函数,并且不会引发任何异常。但是,最后带有const char* what() const noexcept;
表示它不会抛出,这会产生误导。
因此,从C ++ 11开始,我们有了noexcept
说明符。在如下所示的函数声明中使用此函数意味着该函数声明为不引发任何异常。
throw()
注意:"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -nologo -latest -property installationPath > temp.txt
set /p $MSBUILDROOT=<temp.txt
del temp.txt
"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -property installationVersion > temp.txt
set /p $MSBUILDVER=<temp.txt
del temp.txt
set $MSBUILDPATH=%$MSBUILDROOT%\MsBuild\%$MSBUILDVER:~0,2%.0\Bin\MSBuild.exe
已过时,将在C ++ 20中删除。
答案 1 :(得分:1)
const char* what() const throw();
const char*
意味着该方法返回一个指向const char
的指针,该指针是C语言(和C ++,用于向后兼容)中字符串的典型类型
what
是方法名称。
第二个const
表示不允许该方法修改该类的任何非可变成员,或者如果没有标记为mutable
throw()
表示该方法被允许“无”抛出,因此不允许其抛出。可以推断,当引发异常时,此功能应该是您的最后一道防线。在其中抛出异常将破坏目的。