In-class 将 std::unique_ptr 初始化为不完整类型

In-class initialization of std::unique_ptr to an incomplete type

我无法在 Visual Studio 2019 中使用 clang-cl 编译以下代码。虽然 VC++ 编译成功。它还适用于自定义删除器。它应该像示例中那样工作吗?如果不是,为什么?

example.h

#include <memory>

class A;

class B {
    std::unique_ptr<A> a{ make_a() };
    std::unique_ptr<A> make_a();
public:
    B(); ~B();
};

example.cpp

#include "example.h"

class A {};

std::unique_ptr<A> B::make_a() {
    return std::unique_ptr<A>(new A());
}

B::B() = default;
B::~B() = default;

main.cpp

#include "example.h"

int main()
{
    B b;
    return 0;
}

error : invalid application of 'sizeof' to an incomplete type 'A'

Is it supposed to work as it is in the example?

是的,这个例子应该有效。在 A 完成后定义 B::~B 就足够了(也是必要的)。

一些标准规则:

[unique.ptr.general]

... The template parameter T of unique_­ptr may be an incomplete type.

[unique.ptr.dltr.dflt]

The template parameter T of default_­delete may be an incomplete type.


顺便说一句,小建议:

std::unique_ptr<A>
B::make_a() {
    return std::make_unique<A>();
}