Assuming there is no compiler optimization. How many times would OutputBuffer_s type object will be created?
#include <iostream>
#include <vector>
struct OutputBuffer_s {
int encoded[10];
};
OutputBuffer_s func() {
OutputBuffer_s s;
return s;
}
int main() {
OutputBuffer_s a = func();
}
Initially, I had assumed three times.
1) When func() is called, object s
will be created on stack.
2) When func() goes out of scope, it will return copy of object s
to main().
3) Copying of value to object a
in main(), since value returned by func() would be a temporary.
I know that I'm wrong here, since I compiled with -O0
in g++
but I could see only one creation after overriding the constructors. I want to know where and why I am wrong.
a
is copy constructed or even move constructed, becausefunc()
returns an rvalue. – Choroiditisg++
with-O0
is doing some optimizations. – Glaswegian