0

Recently I have run into a problem in a project. The code there is much more complicated than the following example but I hope the problem (if there is one) is the same.

#include <iostream>
class mObject
{
public:
    mObject(){ std::cout << "mObject ctor\n"; }
    mObject(const mObject& other){ std::cout << "mObject copy ctor\n"; }
    ~mObject(){ std::cout << "mObject dtor\n"; }
};

struct cFoo{
    cFoo(const mObject& obj):obj_(obj){}
    const mObject& get() { return obj_;}
    const mObject& obj_;
};

mObject giveme() { return mObject(); }
void func2(const mObject& p) { mObject g = p; }

int main()
{
    cFoo k(giveme());
    func2(k.get());
    return 0;
}

This gives me the following code:

mObject ctor
mObject dtor
mObject copy ctor
mObject dtor

So the original "temporary" mObject instance dies before func2 usese it. I thought life time of a temporary object is extended if there is a const& to it. Assigning return of giveme() to a local const& in funtion main solves this problem. Then the temporary lives until the end of the main's scope. So what is going on here???

Re Captcha
  • 3,125
  • 2
  • 22
  • 34
mecahi
  • 109
  • 2
  • Lifetime extension is for a temporary (or part of a temporary) bound to a local reference. In that case the compiler can simply treat the temporary as a local variable. That's not possible when a reference is passed around in function calls. – Cheers and hth. - Alf Dec 08 '17 at 09:01

1 Answers1

2

Within the same scope of the same function, you can extend the lifetime of an anonymous temporary by binding it to a const reference; for the avoidance of doubt this behaviour is not transitive across function calls.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Uhm, better give an example of what you mean by the "consider `std::reference_wrapper`". As written it sounds as if that can give lifetime extension across function calls. – Cheers and hth. - Alf Dec 08 '17 at 09:06
  • @Cheersandhth.-Alf: Might just tin it, although now this answer seems to be a bit too brief. Let's see how the community reacts. – Bathsheba Dec 08 '17 at 09:08
  • I think it's clearer to say that you can only extend the lifetime of a temporary if a reference to it is taken in the same scope as the temporary. This keeps the temporary alive for the duration of the scope. Here, no reference is taken in the same scope, thus nothing gets extended. – Nikos C. Dec 08 '17 at 09:10
  • @NikosC.; Yes, that is much more correct. Although I hope a more comprehensive answer will emerge. – Bathsheba Dec 08 '17 at 09:11