无法使用std :: unique_ptr< T>其中T是向前声明 [英] Can't use std::unique_ptr<T> with T being a forward declaration
问题描述
现在,我首先了解unique_ptr<>和转发声明的一般问题,如中所述使用unique_ptr?转发声明。
Now first, I am aware of the general issues with unique_ptr<> and forward declarations as in Forward declaration with unique_ptr? .
请考虑以下三个文件:
A.h
#include <memory>
#include <vector>
class B;
class A
{
public:
~A();
private:
std::unique_ptr<B> m_tilesets;
};
C.cpp
#include "A.h"
class B {
};
A::~A() {
}
$ b b
main.cpp
main.cpp
#include <memory>
#include "A.h"
int main() {
std::unique_ptr<A> m_result(new A());
}
发布 g ++ -std = c ++ 11 main .cpp C.cpp
会产生以下错误:
In file included from /usr/include/c++/4.8/memory:81:0,
from main.cpp:1:
/usr/include/c++/4.8/bits/unique_ptr.h: In instantiation of ‘void std::default_delete<_Tp>::operator()(_Tp*) const [with _Tp = B]’:
/usr/include/c++/4.8/bits/unique_ptr.h:184:16: required from ‘std::unique_ptr<_Tp, _Dp>::~unique_ptr() [with _Tp = B; _Dp = std::default_delete<B>]’
A.h:6:7: required from here
/usr/include/c++/4.8/bits/unique_ptr.h:65:22: error: invalid application of ‘sizeof’ to incomplete type ‘B’
static_assert(sizeof(_Tp)>0,
$ b b
这是真的,B是一个不完整的类型在第6行的Ah - 但不是在A的析构函数是!g ++似乎生成一个析构函数,即使我提供一个。A的析构函数在C.cpp行7
That's true, B is an incomplete type in line 6 of A.h - but that's not where A's destructor is! g++ seems to generate a destructor for A even though I am providing one. A's destructor is in C.cpp line 7 and there B is a perfectly defined type. Why am I getting this error?
推荐答案
您还需要将A的构造函数放在C中.cpp:
You also need to put A's constructor in C.cpp:
Ah
#include <memory>
#include <vector>
class B;
class A {
public:
A();
~A();
private:
std::unique_ptr<B> m_tilesets;
};
C.cpp
#include "A.h"
class B {
};
A::~A() {
}
A::A() {
}
查看此答案。构造函数还需要访问完整类型。这是为了在构建过程中抛出异常时可以调用删除器。
See this answer. The constructor needs access to the complete type as well. This is so that it can call the deleter if an exception is thrown during construction.
这篇关于无法使用std :: unique_ptr< T>其中T是向前声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!