没有调用基类构造函数?

时间:2016-11-29 15:57:39

标签: c++ visual-c++ visual-studio-2015 c++14

我正在搜索程序中一个非常奇怪的bug的原因。我发现奇怪的是,基类构造函数由于某种原因未被调用。以下是重现的代码:

struct Parent {
    Parent() : test{9} {}

    int test;
};

template<typename T>
struct Child : T {
    Child() = default;

    // Will obviously not call this one
    template<typename... Args, std::enable_if_t<sizeof...(Args) == 9999>* = nullptr>
    Child(Args&&... args);
};

int main() {
    Child<Parent> test;
    std::cout << "This is a test: " << test.test << std::endl;
}

在我的情况下,程序只会崩溃或打印随机值。

如果我将子类更改为this,则调用构造函数:

template<typename T>
struct Child : T {
    Child() = default;
};

同样的事情,仍然会调用构造函数:

template<typename T>
struct Child : T {
    Child() {}

    // Will obviously not call this one
    template<typename... Args, std::enable_if_t<sizeof...(Args) == 9999>* = nullptr>
    Child(Args&&... args);
};

但是使用第一个定义时,不会调用父构造函数。 我甚至尝试将父构造函数标记为已删除,但它仍然编译并崩溃!

以下是带有已删除构造函数的代码:

struct Parent {
    Parent() = delete;

    int test;
};

template<typename T>
struct Child : T {
    Child() = default;

    // Will obviously not call this one
    template<typename... Args, std::enable_if_t<sizeof...(Args) == 9999>* = nullptr>
    Child(Args&&... args);
};

int main() {
    Child<Parent> test;
    std::cout << "This is a test: " << test.test << std::endl;
}

我正在使用visual studio 2015 update 3。

1 个答案:

答案 0 :(得分:3)

该编译器中的错误。

如果您升级应该有效的Visual Studio 2015版本。

Microsoft's online compiler版本19.10.24631.0(x86)似乎产生了正确的输出。

GCC 6.2.0 and Clang 3.8.0 also appear to produce the correct output

相关问题