I have something similar to the following
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() { };
};
I would like to achieve some constexpr
null constructor for the derived class, but the compiler complains a lot about the two options and similar tests I have done.
Of course the code is more complex, I have an opaque handler and the destructor should behave in a more complex way. The resource free-ing is always the same (no need for multiple destructors, only the Base
one).
I don't know how to achieve this, maybe I am going through a wrong path? Any ideas? I expect to be able to do something like:
Derived a(nullptr);
Derived b(handler1);
Base c (nullptr);
Base d (handler2);
and, in cleanup, both handler1
and handler2
are managed in the some way.
Edit:
Clang (version 3.4) complains:
error: constexpr constructor never produces a constant expression [-Winvalid-constexpr]
And gcc (version 4.8 [edit: multiple versions, haven't checked all]) doesn't complain when using
constexpr Derived(std::nullptr_t) : Base(nullptr) { };
In fact, gcc
seems to do what I wanted to achieve, but I do not understand the constexpr
enough to know which compiler is doing right and how I can amend the problem.