c++ – Initialization and Assignment – Education Career Blog

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?

,

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?

Leave a Comment