Re: Is this valid and moral C++?
David Harmon wrote:
On Sun, 18 Mar 2007 21:09:22 +0100 in comp.lang.c++, Filimon Roukoutakis
<filimon@phys.uoa.gr> wrote,
Suppose that we have a function
f(Object*& obj)
and have declared a global std::vector<Object*> vec;
Is it valid to do
void g() {
vec.push_back(new Object);
f(vec.back());
}
No. The function should receive the pointer argument by value. i.e.
f(Object* obj)
Why?
It is invalid to try to pass a modifiable reference to the result of
.back() , and while a const reference would work it has no particular
advantage.
The call f(vec.back()) does not pass anything "to the result of .back()".
What it does is: it initializes the Object*& parameter of f() with the
result of vec.back(), which so happens to be a reference (non-const in case
the non-const version of back() is called). There is nothing invalid about
it, as far as I can see.
E.g., f() could be:
f ( Object* & p_ref ) {
Object * dummy = new Object ();
std::swap( p_ref, dummy );
delete dummy;
}
Then f(vec.back()) would replace the last pointer with a new pointer whose
pointee has been default constructed.
Secondly, your global vector of Object* will NOT delete the objects
pointed to when it's destructor runs at the end of the program. There's
no big deal about reclaiming the memory at that point, but if Object's
destructor does anything else important you've got a problem.
Right: the vector will not do that by itself. So, the OP will have to take
care of deleting the pointers by himself.
[snip]