I have a function, that returns a reference to an entry in a std::vector
or a null object. I bind this object to a const &
expecting it to point to the original object in the vector:
inline MyClass const & getSomeClassObject( char const * const strName ) const
{
static MyClass nullObj;
for ( auto const & entry : m_myClassObjectsVector )
{
if ( entry.name == strName ) return entry;
}
return nullObj;
}
And this is how the function is called:
MyClass const & myReference = !someOtherObject.isValid() ? m_SomeMemberObject->getSomeClassObject( strName ) : MyClass();
However adding a copy constructor to MyClass
showed that the object is copied on return which causes problems because the temporary lives shorter than m_SomeMemberObject
.
Apparently the conditional operator has something to do with it as removing it will eliminate the copy.
But can someone explain why this happens?