析构函数在这段代码中隐藏在哪里
Where does the destructor hide in this code?
我很难理解为什么Foo
移动构造函数在以下示例中尝试调用~ptr
:
#include <utility>
template <typename T, typename Policy>
class ptr {
T * m_t;
public:
ptr() noexcept : m_t(0) {}
explicit ptr(T *t) noexcept : m_t(t) {}
ptr(const ptr &other) noexcept : m_t(Policy::clone(other.m_t)) {}
ptr(ptr &&other) noexcept : m_t(other.m_t) { other.m_t = 0; }
~ptr() noexcept { Policy::delete_(m_t); }
ptr &operator=(const ptr &other) noexcept
{ ptr copy(other); swap(copy); return *this; }
ptr &operator=(ptr &&other) noexcept
{ std::swap(m_t,other.m_t); return *this; }
void swap(ptr &other) noexcept { std::swap(m_t, other.m_t); }
const T * get() const noexcept { return m_t; }
T * get() noexcept { return m_t; }
};
class FooPolicy;
class FooPrivate;
class Foo {
// some form of pImpl:
typedef ptr<FooPrivate,FooPolicy> DataPtr;
DataPtr d;
public:
// copy semantics: out-of-line
Foo();
Foo(const Foo &other);
Foo &operator=(const Foo &other);
~Foo();
// move semantics: inlined
Foo(Foo &&other) noexcept
: d(std::move(other.d)) {} // l.35 ERR: using FooDeleter in ~ptr required from here
Foo &operator=(Foo &&other) noexcept
{ d.swap(other.d); return *this; }
};
GCC 4.7:
foo.h: In instantiation of ‘ptr<T, Policy>::~ptr() [with T = FooPrivate; Policy = FooPolicy]’:
foo.h:34:44: required from here
foo.h:11:14: error: incomplete type ‘FooPolicy’ used in nested name specifier
Clang 3.1-pre:
foo.h:11:14: error: incomplete type 'FooPolicy' named in nested name specifier
~ptr() { Policy::delete_(m_t); }
^~~~~~~~
foo.h:34:5: note: in instantiation of member function 'ptr<FooPrivate, FooPolicy>::~ptr' requested here
Foo(Foo &&other) : d(std::move(other.d)) {}
^
foo.h:23:7: note: forward declaration of 'FooPolicy'
class FooPolicy;
^
foo.h:11:20: error: incomplete definition of type 'FooPolicy'
~ptr() { Policy::delete_(m_t); }
~~~~~~^~
2 errors generated.
怎么回事?我编写move构造函数是为了避免运行复制器和dtor。请注意,这是一个试图隐藏其实现的头文件(皮条习惯用法),因此使FooDeleter
成为完整类型不是一个选项。
编辑:Bo回答后,我尽可能添加了noexcept
(在上面编辑)。但是错误仍然是一样的。
创建一个包含ptr<something>
成员的新Foo
对象。如果Foo
构造函数失败,编译器必须为部分构造的Foo
的任何完全构造的成员调用析构函数。
但是它不能实例化~ptr<incomplete_type>()
,所以失败了。
私人析构函数也有类似的情况。这也会阻止您创建该类型的对象(除非是从朋友或成员函数中创建的)。
相关文章:
- C++我需要了解在哪里使用指针和双指针
- 未定义的引用在哪里
- 结构和双指针隐藏在其他结构中,多层混淆
- 谷歌测试中的期望值存储在哪里
- 尽管遵循了规则,内存泄漏在哪里
- 静态数据成员模板专用化的实例化点在哪里
- 在哪里放置我的函数?进入我的母语 Gui 还是进入我的演示者?
- 如何等待窗口隐藏在Qt中?
- 在哪里声明结构运算符重载
- C++ 中的自定义异常:在哪里定义它们?
- 常量参数存储在哪里 (C++)?
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 此递归函数的每次迭代的值存储在哪里?
- 如何告诉本机节点模块所需的dll存储在哪里?
- 在哪里存储跨平台C++应用存储?
- C++泛型类错误,问题出在哪里?
- 在标准中,模板参数的语法在哪里定义,例如,'std::function<int(char)>'?
- 将类作为主要参数的语法在哪里需要?
- 析构函数在这段代码中隐藏在哪里
- 隐藏的储藏室在哪里