Is the shared_ptr reference still a pointer?

Recently I have been questioning my work regarding the link shared_ptr

. Here is the code.

for (const auto & aRef : aVec) {
    THROW_RUNTIME_IFNULLPTR(aRef);
    // do sth
}

      

This is my colleague's code. In my opinion, aRef

this is a link that can never be null. Whereas I was told that ( auto &

) aRef

is still a pointer, so it is possible that it is null. The link is to not increment the counter. I am very confused about this.

However, it should be like

for (const auto & aRef : aVec) {
    // THROW_RUNTIME_IFNULLPTR(aRef);
    if ( aRef ) {
        aRef->getX();
    }
    // do sth
} 

      

Am I wrong? I don't think that aRef

is a pointer.

+3


source to share


3 answers


In my opinion, aRef

this is a link that can never be null.

Yes and no. A link can be anything that the object it refers to can refer to. If this object is, say, int

or std::string

or std::vector<double>

, then, of course, it cannot be null (or nullptr

, to be precise).

If this object, however, is a pointer, for example, int*

or void*

, or MyClass*

, then it might be nullptr

, because a pointer might be nullptr

.



Now, in your case, the object being referenced is std::shared_ptr

. It technically can't be nullptr

, but it can represent nullptr

being in the state it get()

returns nullptr

.

Whereas I was told that ( auto &

) aRef

is still a pointer, so it is possible that it is null.

More precisely: it aRef

still appears std::shared_ptr

, so it is possible that it still represents nullptr

.

+8


source


std::shared_ptr

has explicit operator bool()

, so in this code

if ( aRef )

      



this operator will be called and it returns true if the underlying pointer is not null.

+5


source


aRef is a link. This is an alias for the object.

A pointer is a separate object that may be pointing to another object.

In this case, aRef is a reference to an object of the type std::shared_ptr<Something>

.

The code is roughly equivalent to this:

auto first = aVec.begin();
auto last = aVec.end();
for( ; first != last ; ++first) {
    std::shared_ptr<Something> const& aRef = *first;
    if (aRef.get() != nullptr) {
        aRef->getX();
    }
    else {
        // handle the case where aRef is not pointing at an object
    }
}

      

+2


source







All Articles