我有一个B的构造函数,有一些默认参数,取决于其他参数:
struct A
{
int f();
A(const A&) = delete;
A(A&& );
// ....
};
struct B
{
B(A a, int n=a.f()) {//...}
// ...
};
Run Code Online (Sandbox Code Playgroud)
这显然无法以这种方式工作,所以我想使用委托构造函数:
struct B
{
B(A a, int n) {//...}
B(A a): B(a, a.f()) {}
};
Run Code Online (Sandbox Code Playgroud)
但是,这也不起作用,因为删除了A的复制构造函数.所以我需要类似的东西
struct B
{
B(A a, int n) {//...}
B(A a): B(std::move(a), a.f()) {}
};
Run Code Online (Sandbox Code Playgroud)
据我所知,不能保证在std :: move之前评估af(),因此结果是未定义的.是否有可能在std :: move之前获取af()的值,或者我应该更好地编写两个单独的构造函数?
一般说静态对象的析构函数是以与构造函数相反的顺序调用的。据我了解,constinit 对象是在编译时初始化的,因此它们的析构函数应该在“普通”静态对象的析构函数之后调用。
该程序
struct A
{
constexpr A(const char* t): t_(t) {}
~A() {std::cout << "~A(" << t_ << ")\n";}
const char* t_;
};
static A a1("static");
int main () {
static constinit A a2("constinit");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
(使用 GCC 10),但是,给出输出
~A(constinit)
~A(static)
Run Code Online (Sandbox Code Playgroud)
即 constinit 对象在“正常”静态对象之前被销毁(尽管它是更早构造的)。“逆序”规则对 constinit 对象不再有效吗?
如果有一些框架需要类似的类型的回调
void fcn(F& data);
Run Code Online (Sandbox Code Playgroud)
它可以处理ExF类型的异常.
在我的回调中,我使用的是一些抛出EXL类型异常的第三方库.所以我的回调看起来像
void fcn1(F& data)
{
try
{
// call library
}
catch(const ExL& ex)
{
ExF exf = make_ExF(ex);
throw exf;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想写更多回调fcn2,fcn3,...使用库但不想一直重复相同的try/catch.特别是,也许我会添加另一个
catch(const ExL2& ex)
Run Code Online (Sandbox Code Playgroud)
阻止未来几次回调.我无法更改框架和库中的代码(特别是异常类型).如何避免重复try/catch块?
为什么T1和T2具有相同的typeid但类型不同?(输出是1 0)
#include <iostream>
#include <typeinfo>
#include <type_traits>
int main()
{
using T1 = decltype("A");
using T2 = const char[2];
std::cout << (typeid(T1) == typeid(T2)) << "\n";
std::cout << std::is_same_v<T1,T2> << "\n";
}
Run Code Online (Sandbox Code Playgroud) c++ ×4
c++20 ×1
constinit ×1
constructor ×1
delegates ×1
destructor ×1
type-traits ×1
typeid ×1
typeinfo ×1