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?

demonplus
  • 5,036
  • 11
  • 41
  • 56
Johannes Schaub - litb
  • 466,055
  • 116
  • 851
  • 1,175
  • Could you please clarify this: `At some points, we want to store boost::shared_ptr that point to the same data`? You mean you would like to have multiple ownership? – lpapp May 26 '14 at 12:00
  • 1
    Just the idea of `QSharedPointer` sounds wrong. What is the use of it? Looks like you need QVariant instead. – BЈовић May 26 '14 at 12:19
  • FWIW `unique_ptr` is quite handy for RAII handles – sehe May 26 '14 at 12:53
  • It seems to me that the only way to do this is to have common ancestor for all `Ts`. – wilx May 26 '14 at 12:57
  • @sehe So, you want to do something in deleter? How is `unique_ptr` useful? You just wrote what states in the question. – BЈовић May 26 '14 at 13:11
  • @sehe BTW [this Q&A](http://stackoverflow.com/q/19840937/476681) tell it is illegal. – BЈовић May 26 '14 at 13:14
  • @BЈовић I guess I forgot to specify the custom deleter – sehe May 26 '14 at 13:25
  • Is there any reason why you would need to keep the QSharedPointer<>? Couldn't you just change them all to std::shared_ptr<> instead? As far as I know, the only reason to use a Qt pointer is for Widgets and those make use of QPointer instead. So I'm not too sure why that would be required. – Alexis Wilke Jun 02 '14 at 07:55

1 Answers1

2

You cannot define QSharedPointer because void is not a proper type. You could define QSharedPointer and then cast to and from T * and char * Like this:

class A {};

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

Ugly but it works. You may also have to pass in a Deleter which correctly deletes the class to the constructor in order to get your class destructed correctly.

A better alternative would be to use a base class.

jcoffland
  • 4,677
  • 35
  • 40