2

However, class QSharedDataPointer has it.

I always have to define a Class::pointer typedef for shortance and create a pointer with Class::pointer(new Class).

Does anyone know the reasoning for this?

demonplus
  • 5,613
  • 12
  • 49
  • 68
Juriy
  • 565
  • 1
  • 5
  • 17
  • can you give an example sir? – 4pie0 Sep 10 '14 at 10:04
  • You don't want to accidentally convert a shared pointer to a raw pointer and get stuck with a dangling pointer. If you want to store a pointer to an object with shared ownership, store a shared pointer (or weak pointer). If you need to pass a raw pointer to some interface, then you need to make sure the lifetime of the object is long enough. Therefore, implicit conversion from a shared pointer to a raw pointer is asking for trouble. – D Drmmr Sep 10 '14 at 10:19
  • "I always have to..." - no you don't. `ptr.data()` does exactly what you want the operator to do, without the danger of accidentally breaking the shared semantics. – Mike Seymour Sep 10 '14 at 10:32

1 Answers1

1

I suspect the reason why T* () operator doesn't exist is because there's the T* data() function which, like many of the other Qt classes such as QString, QByteArray etc. all provide a data() function to access the underlying data of a Qt class.

This maintains a standard interface across Qt classes.

Also, by overloading the operator, it's very easy to make a mistake if one were to change the underlying data and not realise it here. Using the data() function makes it a bit more obvious what you're doing, in my opinion.

The data() function for QSharedPointer also warns not to delete the returned pointer, or pass it to anything which could delete it, so I see it as a function which is there if you really need it, but better if you can avoid it and if you do use it, think carefully about what is happening.

As for QSharedDataPointer, according to the documentation, calling the operator here calls detach(), making it safe to call.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85