【发布时间】:2012-12-24 17:44:29
【问题描述】:
考虑以下代码:
#include <iostream>
#include <type_traits>
// Abstract base class
template<class Crtp>
class Base
{
// Lifecycle
public: // MARKER 1
Base(const int x) : _x(x) {}
protected: // MARKER 2
~Base() {}
// Functions
public:
int get() {return _x;}
Crtp& set(const int x) {_x = x; return static_cast<Crtp&>(*this);}
// Data members
protected:
int _x;
};
// Derived class
class Derived
: public Base<Derived>
{
// Lifecycle
public:
Derived(const int x) : Base<Derived>(x) {}
~Derived() {}
};
// Main
int main()
{
Derived d(5);
std::cout<<d.set(42).get()<<std::endl;
return 0;
}
如果我想要从Base 公开继承Derived,并且不想在基类中使用虚拟析构函数,那么构造函数 (MARKER 1) 和析构函数的最佳关键字是什么(MARKER 2) 的Base 保证不会发生任何不好的事情?
【问题讨论】:
标签: c++ constructor destructor crtp