我有类似以下内容
class Base {
public:
explicit Base(int* i) noexcept { type = new int; *type = *i; };
constexpr Base(std::nullptr_t) : type(nullptr) { };
~Base() { cout << "Destroying!" << endl; delete type; };
protected:
int* type;
};
class Derived : public Base {
public:
explicit Derived(int* i) noexcept : Base(i) { };
//constexpr Derived(std::nullptr_t) : type(nullptr) { };
//constexpr Derived(std::nullptr_t) : Base(nullptr) { };
~Derived() { };
};
我想实现一些目标constexpr
派生类的 null 构造函数,但编译器对这两个选项和我所做的类似测试抱怨很多。
当然,代码更复杂,我有一个不透明的处理程序,析构函数应该以更复杂的方式运行。资源释放总是相同的(不需要多个析构函数,只需要Base
one).
我不知道如何实现这一点,也许我正在走一条错误的道路?有任何想法吗?我希望能够做类似的事情:
Derived a(nullptr);
Derived b(handler1);
Base c (nullptr);
Base d (handler2);
并且,在清理过程中,两者handler1
and handler2
以某种方式进行管理。
Edit:
Clang(3.4 版)抱怨:
error: constexpr constructor never produces a constant expression [-Winvalid-constexpr]
并且 gcc (版本 4.8 [编辑:多个版本,尚未检查全部])在使用时不会抱怨
constexpr Derived(std::nullptr_t) : Base(nullptr) { };
实际上,gcc
似乎做了我想要实现的目标,但我不明白constexpr
足以知道哪个编译器做得正确以及我如何修改问题。