Recently I have a doubt in my work about the reference of a shared_ptr. Here is the code.
for (const auto & aRef : aVec) { THROW_RUNTIME_IFNULLPTR(aRef); // do sth } This is the code of my colleague. In my mind, aRef is a reference which can never be null. While I was told that (by auto &) aRef is still a pointer so it's possible that it's null. The reference is just to not increment the counter. I'm very confused about that.
However, it should be like
for (const auto & aRef : aVec) { // THROW_RUNTIME_IFNULLPTR(aRef); if ( aRef ) { aRef->getX(); } // do sth } Am I wrong about this? I don't think that aRef is a pointer.
aVec? What type?shared_ptris a reference-counted pointer. Every time theshared_ptris copied, the reference count is increased. Every time a copy is destroyed, the count is decreased. When the reference count hits zero, the pointer isdeleteed. By usiung a reference, theshared_ptris not copied, saving the copy construction and destruction and thus reference count overhead.