当我学习使用异常时,我刚刚想到了一个问题。代码如下。
// exception constructor
#include <iostream> // std::cout
#include <exception> // std::exception
#include <cxxabi.h>
#define PRINT_TYPENAME(f) std::cout << abi::__cxa_demangle(typeid(f).name(), 0, 0, &status) << std::endl;
struct ooops : std::exception
{
const char *what() const noexcept { return "Ooops!\n"; }
};
int main()
{
ooops e;
std::exception *p = &e;
// demangle the typeid
char *realname;
int status;
PRINT_TYPENAME(p);
PRINT_TYPENAME(*p);
try
{
throw e; // throwing copy-constructs: ooops(e)
}
catch (std::exception &ex)
{
std::cout << ex.what();
}
try
{
throw *p; // …Run Code Online (Sandbox Code Playgroud) 我在学习通用(转发)参考时发现了这个问题。代码如下。
\n#include <iostream> // std::cout\n\n#include <type_traits>\n\ntemplate <class T> // deductions among universal reference\nvoid fun(T &&b) // fold reference, maintain const\n{\n std::cout << b << " ";\n std::cout << std::is_const<T>::value << " ";\n std::cout << std::is_lvalue_reference<T>::value << " ";\n std::cout << std::is_rvalue_reference<T>::value << std::endl;\n}\n\nint main()\n{\n int a = 1;\n fun(a); // lvalue: T=int&\n fun(std::move(a)); // rvalue: T=int\n\n const int ca = 1;\n fun(ca); // const_lvalue: T=int& \xef\xbc\x88why no const?\xef\xbc\x89\n fun(std::move(ca)); // const_rvalue: T=const int\n\n int &la = a;\n fun(la); // …Run Code Online (Sandbox Code Playgroud)