Rick de Water
Rick de Water

Reputation: 2642

constexpr with delegating constructors

I have to following code:

class IP4Address
{
    public:
    constexpr IP4Address();
    constexpr IP4Address(uint32_t a_IP, uint16_t a_Port);

    private:
    uint32_t m_IP;
    uint16_t m_Port;
};

constexpr IP4Address::IP4Address():
    IP4Address(0, 0)
{

}

constexpr IP4Address::IP4Address(uint32_t a_IP, uint16_t a_Port):
    m_IP(a_IP),
    m_Port(a_Port)
{

}

Which results in the following errors (Visual Studio 2015):

error C2476: 'constexpr' constructor does not initialize all members
note: 'IP4Address::m_IP' was not initialized by the constructor
note: 'IP4Address::m_Port' was not initialized by the constructor

Is this invalid C++? Am I doing something wrong? Or is this possibly a compiler bug?

Upvotes: 2

Views: 875

Answers (1)

HelloWorld
HelloWorld

Reputation: 1863

This is a bug in MSVC 2015. The C++ 11 documentation §7.1.5 4 says in a pretty clear manner:

4. The definition of a constexpr constructor shall satisfy the following constraints:

4.1 the class shall not have any virtual base classes

4.2 each of the parameter types shall be a literal type

4.3 its function-body shall not be a function-try-block;

In addition, either its function-body shall be = delete, or it shall satisfy the following constraints:

4.4 either its function-body shall be = default, or the compound-statement of its function-body shall satisfy the constraints for a function-body of a constexpr function;

4.5 every non-variant non-static data member and base class sub-object shall be initialized

4.6 if the class is a union having variant members (9.5), exactly one of them shall be initialized;

4.7 if the class is a union-like class, but is not a union, for each of its anonymous union members having variant members, exactly one of them shall be initialized;

4.8 for a non-delegating constructor, every constructor selected to initialize non-static data members and base class sub-objects shall be a constexpr constructor;

4.9 for a delegating constructor, the target constructor shall be a constexpr constructor.

Your class matches all criterias. Clang and GCC also accept your source so I would be surprised if I overlooked something.

Upvotes: 4

Related Questions