【发布时间】:2015-04-15 19:32:33
【问题描述】:
如果我有一个类“酒吧”:
// bar.h
class Bar
{
public:
Bar() { }
};
我转发声明与另一个类 'Foo' 中的 std::unique_ptr 一起使用:
// foo.h
#include <memory>
class Bar;
class Foo
{
public:
Foo();
private:
std::unique_ptr<Bar> bar_;
};
我在 Foo 的实现文件中包含了它的定义:
// foo.cpp
#include "foo.h"
#include "bar.h"
Foo::Foo()
: bar_(new Bar)
{ }
我收到编译时错误“'sizeof' 对不完整类型 'Bar' 的无效应用”。
我从here 和here 了解到,为了解决这个问题,我可以在 foo.h 中声明 Foo 的析构函数并将其空定义移动到 foo.cpp。我不明白的是,为什么要解决它。我读到 std::unique_ptr 有时需要知道其类型的完整定义。如果我必须从 bar.h 中包含 Bar 以便 unique_ptr 看到它的定义,这对我来说是有意义的。但是 Foo 的析构函数与 Bar 的可见性有什么关系,为什么在 foo.h 中声明 ~Foo() 并在 foo.cpp 中定义它会消除错误?
【问题讨论】:
标签: c++ c++11 std smart-pointers