Force return-by-reference function to make a copy?

Started by
12 comments, last by SiCrane 11 years, 4 months ago
If you really wanted to do this you could use:

T SortedList<T>::Delete(void) {
T temp(m_pFront->GetData());
// do the deletion logic
return temp;
}
Advertisement

If you really wanted to do this you could use:

T SortedList<T>::Delete(void) {
T temp(m_pFront->GetData());
// do the deletion logic
return temp;
}



Wait...so is the C-style initialization the only way to copy the reference value? In other words, this does work / is not allowed?

T noCopy = m_pFront->GetData();
That should work if T has a copy constructor. It will make a copy though, so noCopy is not a good name for the variable ;)
"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley
T temp(initializer); and T temp = initializer; will both create a copy of the the object. However, the first form is a direct initializer and the second form is a copy initializer. Under most circumstances you can treat them as the same, but there are times when the first will work but the second won't.

This topic is closed to new replies.

Advertisement