在类中将不完整类型的unique_ptr初始化为 nullptr 时编译 gcc 错误
Compile error with gcc when in-class initializing unique_ptr of incomplete type to nullptr
我正在使用带有unique_ptr的pimpl习语编写一些代码。当我尝试使用类内初始化将unique_ptr设置为默认的nullptr时,gcc给出了编译错误,而clang和msvc都成功编译了代码。如果我不使用类内初始化,错误就会消失。
// A.h
#pragma once
#include <memory>
using namespace std;
class B;
class A
{
private:
////////////////////////
// here gives the error!
////////////////////////
unique_ptr<B> impl{nullptr}; // error only with gcc,
// ok with clang and msvc
unique_ptr<B> impl2; // ok with all three
public:
A();
~A();
};
// A.cpp
#include "A.h"
class B
{
private:
int b{5};
public:
B() = default;
~B() = default;
};
A::A() = default;
A::~A() = default;
// main.cpp
#include "A.h"
int main()
{
A a;
return 0;
}
当我编译上面的代码时,gcc抱怨"错误:将'sizeof'无效地应用于不完整的类型'B'"。我已经尝试了 gcc 8.3 和 gcc 9.1 但没有成功。这是编译器错误吗?谢谢!
编辑:我按照@eerorika建议尝试。如果头文件和源文件合并为一个文件,它可以正常编译,但不能分开。
编辑确认是编译器错误,并且已在 gcc9.2 中修复。
该程序,特别是默认成员初始化器,格式正确。如果编译器拒绝编译,那么据我所知,这是编译器中的一个错误。
我可以重现GCC 9.1的问题,但不能重现9.2或主干的问题,因此它似乎已修复。对于旧版本,您可能需要放弃使用默认成员初始化器作为解决方法。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在malloc()之后初始化结构中对ptr的引用
- 唯一ptr初始化断言失败
- 使用boost lambda构造创建初始化的智能ptr的容器
- "int* ptr = int()"值初始化如何不违法?