基类构造函数未调用
Base class constructor not called?
我正在搜索程序中一个非常奇怪的错误。我发现奇怪的是,由于某种原因,基类构造函数没有被要求。这是复制的代码:
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似乎也产生正确的输出
相关文章:
- 在c++中使用向量时,如何调用构造函数和析构函数
- C++:考虑但不调用构造函数的特殊性
- 对象实例化调用构造函数的次数太多
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- C ++:通过大括号调用构造函数?
- 不能调用构造函数
- 赋值 boost::intrusive_ptr 而不调用构造函数?
- 在模板化类的构造函数中调用构造函数
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- 有没有一种简单的方法可以在对象向量上调用构造函数?
- 我不明白在这个例子中什么时候调用构造函数
- 调用c++构造函数的不同方法
- 调用构造函数与将内联常量定义为默认参数
- 如何通过 Rust FFI 调用C++构造函数?
- "new"运算符是否总是调用构造函数?
- 无法调用构造函数
- 使用 "()" 调用构造函数不同于"{}"
- 确定是调用构造函数还是强制转换运算符的因素