基类构造函数未调用

Base class constructor not called?

本文关键字:调用 构造函数 基类      更新时间:2023-10-16

我正在搜索程序中一个非常奇怪的错误。我发现奇怪的是,由于某种原因,基类构造函数没有被要求。这是复制的代码:

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;
}

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

如果我将子类更改为此,则称为构造函数:

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更新3。

该编译器中的错误。

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

Microsoft的在线编译器在版本19.10.24631.0(x86)似乎产生了正确的输出。

gcc 6.2.0和clang 3.8.0似乎也产生正确的输出