warning: taking address of temporary

Jun 14, 2011 at 8:34pm
Ok, I understand what is going wrong.
But how wrong is wrong?
Can I use it?

1
2
3
4
5
6
int func(const class MyClass *a) { return a->int_member; }

int main() {
   func(&MyClass());
   return 0;
}
Jun 14, 2011 at 8:36pm
It's a warning because you could use that address outside of the scope of the temporary and have an invalid pointer.
Jun 14, 2011 at 8:36pm
closed account (zb0S216C)
Why are you calling MyClass's constructor as an argument? This doesn't make any sense to me.

Wazzak
Jun 14, 2011 at 9:06pm
He's instantiating a class object on-the-fly, Framework, just for testing purposes.
Jun 14, 2011 at 9:23pm
Ok, so I can use it in my code without problems on different compilers.
Jun 14, 2011 at 9:36pm
He can avoid the warning by using a reference rather than pointer:

1
2
3
4
5
6
7
8
int func(  const MyClass & a) { return a.int_member; }

int main()
{
    func(MyClass());

    return 0;
}


Jun 15, 2011 at 1:03am
Ok, so I can use it in my code without problems on different compilers.

No, that's not valid C++. Use a reference, as mentioned.
Topic archived. No new replies allowed.