0

I have a class with a function that returns a copy of a private member:

class MyClass
{
    MyString str;

public:

    MyString getStr() { return str; }
}

Another function, func, takes in a const &MyString that is bound to a statement handle. When I invoke func(o.getStr()), the copy object returned by getStr goes out of scope after the func call and is no longer valid for the statement handle. I can create a local variable MyString ms = o.getStr() and then pass that to func, but I don't want to have to do that multiple times for different getters. Also, func needs to take in a ref since sometimes I need to pass in a local variable and change the value of it after subsequent uses of the statement handle. Is there a good solution to this?

  • store it in a local variable of type MyString initaly and use it as arg for fn func. So you can use the it later from this variable – 999k Mar 07 '14 at 22:18
  • Possible duplicate of http://stackoverflow.com/questions/11560339/returning-temporary-object-and-binding-to-const-reference – harmic Mar 07 '14 at 22:59
  • The lifetime of the return value of `o.getStr()` is until the end of the **statement** that it occurs on. In particular, it still exists for the entirety of the call to `func`. I'm not sure what you are saying about "func use the ref afterwards", `func` cannot do anything once it has returned. Maybe showing your code for `func` would help. – M.M Mar 08 '14 at 01:54
  • It turned out that I needed getStr() to return a const ref. – user2971092 Nov 11 '15 at 12:24

1 Answers1

1

The MyString copy that getStr() returns will not go out of scope until func() exits, ensuring that func() can access the copy.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770