使用CRTP时确保安全
Ensure safety while using CRTP
考虑以下使用CRTP 的代码片段
#include <iostream>
struct Alone
{
Alone() { std::cout << "Alone constructor called" << std::endl; }
int me {10};
};
struct Dependant
{
explicit Dependant(const Alone& alone)
: ref_alone(alone)
{ std::cout << "Dependant called with alone's me = " << alone.me << std::endl; }
const Alone& ref_alone;
void print() { std::cout << ref_alone.me << std::endl; }
};
template <typename D>
struct Base
{
Base() { std::cout << "Base constructor called" << std::endl; }
D* getDerived() { return static_cast<D*>(this); }
Dependant f { getDerived()->alone };
void print() { f.print(); }
};
struct Derived : Base <Derived>
{
Derived() { std::cout << "Derived constructor called " << std::endl; }
Alone alone {};
void print() { Base::print(); };
};
int main()
{
Derived d;
d.print();
}
原始链接http://coliru.stacked-crooked.com/a/79f8ba2d9c38b965
我有一个基本问题首先
使用继承时如何进行内存分配?我知道构造函数是从Base调用到Derived的,但当我进行时
派生d;
分配相当于sizeof(D)的内存,然后调用构造函数。我的理解正确吗?(这将解释打印未初始化的成员)
考虑到上面的例子,当涉及到CRTP时,你会建议/推荐任何最佳实践吗?
分配相当于sizeof(D)的内存,然后将构造函数称为
否则它怎么可能工作呢?不能在内存中构造尚未分配的对象。内存分配总是先于对象构造。
考虑到上面的例子,当涉及到CRTP时,你会建议/推荐任何最佳实践吗?
CRTP的标准做法是:不要在构造函数/析构函数中调用CRTP。虚拟函数也是如此。虚拟是动态多态性,而CRTP是静态多态性。但它们都使用相同的基本机制:基类定义派生类必须实现的接口。
就像使用虚拟函数一样,试图在构造函数/析构函数中调用它并不能达到你的目的。唯一的区别是,使用虚拟函数,编译器实际上会阻止您获得未定义的行为。而使用CRTP,您只会出现破损。
请注意,这包括默认的成员初始值设定项,出于非聚合的目的,它们只是构造函数初始化列表的简写。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 如何确保C++函数在定义之前声明(如override关键字)
- 虚拟决赛作为安全
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 如何将元素添加到数组的线程安全函数?
- C++中的线程安全删除
- 通过网络、跨平台传递std::变体是否安全
- 确保无变体的型号安全
- 确保静态布尔检查的线程安全
- 可靠地确保C++ 14 中的内存安全
- 使用原子指令确保映射访问安全,是否可以使用两个不同的原子对指令进行重新排序
- 生产者/使用者,如何确保在关闭所有使用者之前耗尽线程安全队列
- 使用CRTP时确保安全
- 增强串行化:通过套接字传输确保数据安全
- 如何确保从函数返回指针是安全的
- 使用自己开发的软件确保条形码安全
- 正确使用std智能指针以确保ptr安全
- 在映射中使用std::thread::id可以确保线程安全
- C++ - 一种确保调用全局清理函数的异常安全方法