Re: reference to a vector
benben wrote:
The memory layout is most likely the same as a double so memsetting it
has the same effect of memsetting a double.
If the memory layout is most likely the same as a double, then
memsetting it might have the same effect as memsetting a double.
Agreed. It's horrible, and quite possibly UB.
I don't see it that way. I think it is just a simple matter made
complicated but the behavior is still well defined (but platform
dependent.)
The behavior is undefined. That doesn't mean that it won't do what you
expect. It means that if you do that, you're outside the realm of the
C++ language definition. The danger is twofold: there's the slight
chance that all 0's for a floating-point type isn't 0.0, and there's the
greater change that the compiler puts some internal data in the object
that shouldn't be set to 0. So, in a nearly meaningless sense, it is,
indeed, platform dependent: what happens depends on your compiler. But
it's definitely not well defined.
The definition could have been trivially the following:
The definition SHOULD have been the following:
struct bar {
double variable;
bar():variable(0.0){}
bool operator <( bar & f) const{
return variable > f.variable;
}
};
I'm all in favor of taking advantage of formally undefined behavior in
appropriate cases. In this case it isn't appropriate, because the
well-defined, portable form of initialization works just fine.
No, ptr_f is a pointer to memory allocated from the free store. The
memory doesn't go away when run_it() exits, and run_it returns a
reference to the vector allocated on the free store. The problem is
that the memory leaks -- there's no way to delete the new'ed vector.
I agree with you that the memory in OP's code is leaked. But it is
possible, though, to delete that memory. Simply
delete &f;
NO!!!!
std::vector<bar > f = run_it();
Sorry to shout, but f is a COPY of the object that the returned
reference referred to. It will be destroyed at the end of main. Deleting
it will blow things up horribly, because f was not allocated on the free
store.
--
Pete Becker
Roundhouse Consulting, Ltd.