1

If I write this code:

QSharedPointer<int> ptr(new int());  

The number of references pointing to the integer is 1.
But when I call data() like this:

QSharedPointer<int> ptr(new int());   
int* ptr2 = ptr.data();  

Is the number of references 1 or 2 ?
Thanks for help.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
Random Coder 99
  • 376
  • 1
  • 15
  • In terms of QSharedPointer caling data() does not increment reference count in that QSharedPointer, so if you call ptr.clear() then it will destroy the hold object and ptr2 will point to non existent data in memory. But there might be some ambiguousness in the question what do you mean by references - what is ref counts in QSharedPointer or how many variables are pointing to the object in the code. – Evgeny S. Mar 13 '16 at 15:48

2 Answers2

4

It won't change. QSharedPointer only shares the pointer with QSharedPointer. It won't and can't share with raw pointer.

QSharedPointer will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it.

And QSharedPointer::data() does nothing except

Returns the value of the pointer referenced by this object.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
4

Calling data() does not change reference count. In fact, it doesn't really do anything. Its implementation is just this

inline T *data() const { return value; }

This is taken directly from Qt sources.

Sergei Tachenov
  • 24,345
  • 8
  • 57
  • 73