带有委派构造函数的 constexpr

constexpr with delegating constructors

我必须遵循以下代码:

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)
{

}

这会导致以下错误 (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

这是无效的 C++ 吗?难道我做错了什么?或者这可能是编译器错误?

这是 MSVC 2015 中的一个错误。C++ 11 文档 §7.1.5 4 非常清楚地说明:

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.

您的 class 符合所有条件。 Clang and GCC 也接受你的来源,所以如果我忽略了什么,我会感到惊讶。