Search code examples
c++operator-precedence

Can I use the object in the same expression more than once without modifying it safely?


I've seen this example on C++ primer 5 edition which talks about smart pointers; I have class StrBlobPtr which works as a companion to StrBlob.

One of the members of StrBlobPtr is deref:

std::string& StrBlobPtr::deref() const
{
    auto p = check(curr, "dereference past end");
    return (*p)[curr]; // (*p) is the vector to which this object points
}

check returns a std::shared_ptr either null or pointing to an object.

  • What I want to know only is whether I can make the return statement directly from calling check or not:

    std::string& StrblobPtr::deref() {
        return (*check(index_, "dereferencing unbound StrblobPtr!"))[index_];
    }
    
  • So is it well-defined here using index_ in the same expression twice without modifying it? Thank you!


Solution

  • Using index twice in

    return (*check(index_, "dereferencing unbound StrblobPtr!"))[index_];
    

    fine as long as you are not modifying it.

    What is not fine though is you are unconditionally indirecting the pointer. You say check can return a null pointer. Indirecting through a null pointer is undefined behavior. You need to make sure you guard against that by checking the return value first. If it is null then you either need to return a sentinel or throw an exception.