views:

134

answers:

1

I have some 'legacy' code (which I can't change, but need to add on to) that looks something like this:

template<typename T> T Foo(T& target)
{
    //Assign to 'target', but never read from it before that.
    //Also, 'target' is going to be a POD-type.

    target = T();

    return target;
}

int main()
{
    float value = Foo(value);
}

This feels unsafe (i.e., making sure that target is never assigned to before it's used), are there any other potentially lethal problems with this sort of interface?

+1  A: 

Well.. If you do the code:

T value;

then value will get it's constructor called on it. The template honestly just looks like the constructor is just getting called twice.

Also, if T is just plain old data, then there is no lethal problem that could occur...

What exactly are you worried about occurring?

sharth
Well, when Foo's scope is entered, target (a.k.a, value in main) isn't properly initialized; that could cause problems if it's accidentally read in Foo before it's assigned something meaningful.
Ooo. Hmm. I honestly don't know if the constructor would have been called by that point... For plain old data, I wouldn't worry too much, since you're going to have stack space reserved though. The worst case that I can think of is that you are going to have nonsense in there.
sharth
Same concern. Is it UB to read an uninitialized POD-type?
Actually, I just tried it out with gcc, and the constructor hasn't been called at that point. That's quite cool actually. Worst case scenario is that you access data that is uninitalized. With POD types though, you won't get seg faults or anything like that.
sharth
It shouldn't be. In any sense of how the memory is laid out, you're just accessing memory on the stack or within a register. Just because the constructor hasn't been called doesn't mean that the memory hasn't been allocated (if it's stack space, it should have been allocated at compile time)
sharth