Understanding [] operator in ReferenceCountedArray


Hi all,

I have a simple class Thing:

class Thing : public ReferenceCountedObject
	typedef ReferenceCountedObjectPtr<Thing> Ptr;

and a ReferenceCountedArray with one thing in it. While printing out the number or references I found something not 100% clear to me:

	ReferenceCountedArray<Thing> things;
	Thing::Ptr thing = new Thing();

	std::cout << thing->getReferenceCount() << " things around\n";  // prints 1, OK (1 thing)


	std::cout << thing->getReferenceCount() << " things around\n"; ; // prints 2, OK (1 thing + 1 ref in the array)
	std::cout << things[0]->getReferenceCount() << " things around\n"; ;  // prints 3: ???
	std::cout << things.getObjectPointer(0)->getReferenceCount() << " things around\n"; ; // prints 2, OK (1 thing + 1 ref in the array)

I was expecting things[0]->getReferenceCount() to print 2, but the result was 3 . Looking at the source code, Is it because ReferenceCountedArray::operator[] returns a ReferenceCountedObjectPtr where a temporary object creation is somehow involved?

Hope I’m not completely off the track here. Thanks in advance :star:


Yes that’s right. In the things[0] version the temporary exists until the call to getReferenceCount() is complete. Until you’re sure what you’re doing then you should probably always refer to your ReferenceCountedObjects using ::Ptr. The reason for the existence of the getObjectPointer() method will be as an optimisation where you are sure that the additional increment and decrement is unnecessary and you know for certain that it is safe to refer directly to the raw pointer.


Thanks @martinrobinson, that was very informative.