gpt4 book ai didi

c++ - 为什么 boost::scoped_ptr 会阻止 BCB6 的 PIMPL 习语?

转载 作者:行者123 更新时间:2023-11-30 03:53:02 25 4
gpt4 key购买 nike

我正在尝试将 boost::scoped_ptr 与我的实现类一起使用,它仅在包含类的 cpp 文件中可见。包含类有一个显式定义的析构函数(不是内联的),但我的编译器 (Borland C++ 5.6.4) 无法编译。

如果我改用 boost::shared_ptr,同样的示例会按预期编译和运行。

我做错了什么?


编辑:抱歉忘记在此处显示源代码、编译器错误和(预期的)输出:

源代码

文件check_shared.cpp:

// shortened.
#include "SmartPtrTest.h"
void check_shared()
{
Containing t;
}

文件SmartPtrTest.h:

#include <boost/noncopyable.hpp>
#include <boost/smart_ptr.hpp>

class Impl;
#define smart_ptr boost::scoped_ptr

class Containing: private boost::noncopyable
{
public:
Containing();
~Containing();
private:
smart_ptr<Impl> impl;
};

文件SmartPtrTest.cpp:

#include "SmartPtrTest.h"
#include <iostream>

using namespace std;

class Impl {
public:
Impl() {
cout << "ctr Impl" << endl;
}
~Impl() {
cout << "dtr Impl" << endl;
}
};

Containing::Containing(): impl(new Impl)
{
cout << "ctr Containing" << endl;
}

Containing::~Containing()
{
cout << "dtr Containing" << endl;
}

编译错误

...类似于 undefined structure 'Impl'(德语:Undefinierte Struktur 'Impl')。编译文件 check_shared.cpp 时,编译器在该函数的 typedef 中的文件 boost/checked_delete.hpp 中停止:

template<class T> inline void checked_delete(T * x)
{
// intentionally complex - simplification causes regressions
typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
(void) sizeof(type_must_be_complete);
delete x;
}

输出(预期)

我在使用 boost::share_ptr 时得到的输出显示 ctr 和 dtr 已按预期调用。

ctr Impl
ctr Containing
dtr Containing
dtr Impl

最佳答案

只要“实现”类在智能指针可能被销毁的任何点完成,这就应该起作用。这不仅发生在析构函数中,而且发生在构造函数中 - 如果它们由于异常而退出,则必须销毁指针成员。

因此请确保您的构造函数和析构函数在源文件中定义在实现类的定义之后。

(这是基于您因试图销毁不完整的类型而导致编译错误的猜测。如果您遇到不同的错误,或意外的运行时行为,或更改未修复它,请更新问题来演示实际问题。)

关于c++ - 为什么 boost::scoped_ptr 会阻止 BCB6 的 PIMPL 习语?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30323862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com