0

I have been learning C++ and programmed this out of curiosity:

#include <iostream>

class A {};

class B {
    public:
        ~B() {}
};

A get_a() {
    A a;
    std::cout << &a << '\n';

    return a;
}

B get_b() {
    B b;
    std::cout << &b << '\n';

    return b;
}

int main() {
    A a = get_a();
    std::cout << &a << '\n';

    B b = get_b();
    std::cout << &b << '\n';

    return 0;
}

I got this as the ouput:

0x61fedf
0x61ff0f
0x61ff0e
0x61ff0e

This implies that a new object is constructed in the case of A, but the lifetime of B is simply extended.

Can anyone explain this to me? I am currently writing a library and don't want to have any incorrect preconceptions.

  • It seems that the compiler does [RVO](https://en.wikipedia.org/wiki/Copy_elision#Return_value_optimization) for `get_b` but not for `get_a`. It couyld have something to do with `A` being an empty object. Not that it matters, if you return an object by value, you should always treat the returned object as a new unique copy. – Some programmer dude May 23 '20 at 09:56
  • Same explanation presented here https://stackoverflow.com/questions/48879226/does-the-behavior-of-guaranteed-copy-elision-depend-on-existence-of-user-defined – StoryTeller - Unslander Monica May 23 '20 at 10:27

1 Answers1

0

This is most likely an optimization feature of your compiler. For example, when I compiled your code using CL (MSVC compiler) without any optimization option, I got the following results:

enter image description here

But turning on fast code option, resulted in a more optimized memory usage:

enter image description here

Commands for disabled and fast code options of CL, respectively:

>cl /OD app.cpp
>cl /O2 app.cpp

You should refer to your compiler documentations to figure out the optimization options.

Omid
  • 286
  • 1
  • 5
  • 20