I have some classes kind of like this:
struct Foo {
char *data;
Foo(args) { /* initialize data */ }
~Foo() { /* clean up data */ }
};
struct Bar {
...
Foo getFoo() const { /* properly initialize and return a Foo */ }
};
And I want to do this:
memcpy(dst, barInstance.getFoo().data, size);
My question is the memcpy
well-defined, or will the temporary Foo
's destructor leave me with a dangling pointer before the invocation of memcpy
? (assume dst
, and size
are correct.)
I know there is a very simple workaround by writing
{
Foo tmp = barInstance.getFoo();
memcpy(dst, tmp.data, size);
} // tmp destructed here after memcpy()
but I am curious if it is necessary.