mercredi 18 septembre 2019

Can an object of class type T be constant initialized when T has a non-trivial destructor?

Let's look at this sample of code:

class D
{
    public:
    constexpr D(int val) : i(val) { };
    ~D() { };

    private:
    int i;
};

D d(3);

According to the documentation, D should be constant initialized:

Only the following variables are constant initialized: [...]
2. Static or thread-local object of class type that is initialized by a constructor call, if the constructor is constexpr and all constructor arguments (including implicit conversions) are constant expressions, and if the initializers in the constructor's initializer list and the brace-or-equal initializers of the class members only contain constant expressions.

Indeed, d is initialized by constructor call, the constructor of D is constexpr and my argument (3) is a constant expression.

However, to specify to the compiler the value of a variable can be evaluated at compile time, it is possible to use constexpr specifier. But, in this case, it won't compile because D is not a LiteralType because it define a non-trivial constructor.

So, in my snippet, is d really constant initialized? If so, why can't I use constexpr specifier?

Aucun commentaire:

Enregistrer un commentaire