Right way to return a local variable

Hi guys,
I know that this is not good C++ form at all, right?:
1
2
3
4
5
Mytype func(Mytype my)
{
    Mytype m = my;
    return m;
}

This is bad because I am returning a reference to a local variable that is destroyed. But is this good C++:
1
2
3
4
5
int func(int f)
{
    int g = f;
    return g;
}

Is that good? Now that I think about it, how would you return any variable from any function? This is leading me to think that my conception of "A local variable should not be returned from a function".
Is that rule supposed to read: "Do not return a pointer to a local variable"?
Any thoughts would be appreciated.
Last edited on
Your two examples are the same. However there are a few things going on here. One is that you must not return a pointer or reference to an object that is about to go out of scope (a local variable). The second is that people have a (well reasoned) gripe with code like this:
1
2
3
4
int increment(int x) {
    int total = x + 1;
    return total;
}

This code works fine, because it returns by value, however it is better written like this:
1
2
3
int increment(int x) {
    return x + 1;
}
Ok, thanks!
Topic archived. No new replies allowed.