4 ms·
No. If your function does "return <some local var>", as in Foo xyzzy() { Foo ret; /* do stuff to ret */ return ret; } then th
by tbrownaw 16y ago
No.
If your function does "return <some local var>", as in
Foo xyzzy() {
Foo ret;
/* do stuff to ret */
return ret;
}
then the compiler can rewrite it to be something like
void xyzzy(void * _ptr) {
Foo * _ret = new(_ptr)Foo();
/* do stuff to *_ret */
}
where the function-local variable that gets returned is actually just constructed in the place that it would eventually be returned/copied to and so doesn't have to be returned at all.
- pdovy 16y agoThis would introduce another performance consideration though, wouldn't it? You may not be paying the cost for the explicit copy, but now you are paying the cost of allocating space for a Foo on the heap instead of the stack. It would depend on the situation, but this seems like it might just be wash at the end in terms of performance?
- 124816 16y agoThat weird new(T* )T(...) syntax is how you ask c++ to run the constructor of T on an existing T* . (In this case that T* would point to the stack.) Note that the memory at the T* shouldn't be a real T; or if it is, its destructor ought to be run first.