在类中将不完整类型的unique_ptr初始化为 nullptr 时编译 gcc 错误

Compile error with gcc when in-class initializing unique_ptr of incomplete type to nullptr

本文关键字:初始化 ptr nullptr 错误 gcc 编译 unique 类型      更新时间:2023-10-16

我正在使用带有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或主干的问题,因此它似乎已修复。对于旧版本,您可能需要放弃使用默认成员初始化器作为解决方法。