6

For historical reasons, I use QSharedPointer<T> in my software. At some points, we want to store boost::shared_ptr<T> that point to the same data, and which should keep alive the instances of the QSharedPointer<T>.

The common way to do this is to keep a copy of the other smart pointer within the deleter of boost::shared_ptr<T>. But to prevent the deleter from having different types for different Ts, which would prevent easily getting a QSharedPointer back with boost::get_deleter, when the corrresponding boost::shared_ptr has been upcast, I wanted to store the original QSharedPointer<T> as a QSharedPointer<void> within the deleter, as opposed to using the T.

But I find that QSharedPointer is not up to the task, as it throws errors like "reference to void can't be done", when compiling its header.

Does anyone have an idea on how to make this work without exposing T into the deleter?

4

1 回答 1

2

您不能定义 QSharedPointer 因为 void 不是正确的类型。您可以定义 QSharedPointer ,然后在 T * 和 char * 之间进行转换,如下所示:

class A {};

QSharedPointer<char> x((char *)new A);
A *ptr = (A *)x.data();

丑陋但有效。您可能还必须将正确删除类的 Deleter 传递给构造函数,以便正确销毁您的类。

更好的选择是使用基类。

于 2014-05-28T20:38:28.870 回答