4

I was wondering if returning *this from a function is safe. this question shows some ways you can do it and my question is given this example:

struct test {
    string t;
    string b;
public:
    test& A(string test)       { this->t=test; return *this; }

    test& B(string test)       { this->b=test; return *this; }
};

int main() {

    auto a = test().A("a").B("b").A("new a");
    return 0;
}

Is there going to be memory leakage?

Community
  • 1
  • 1
GlacierSG
  • 469
  • 4
  • 14
  • 6
    Which memory are you thinking may leak? – Kerrek SB Mar 23 '17 at 17:39
  • 5
    Why would there be any memory leak? I see no allocation and no dangling pointers. – abelenky Mar 23 '17 at 17:39
  • 2
    If you don't ask for any memory you can't leak it. – Galik Mar 23 '17 at 17:40
  • 4
    Certain operations, like `operator=` are **required** to return a reference to `*this`. So yes, it is perfectly safe. It is a form of [fluent-style coding](https://en.wikipedia.org/wiki/Fluent_interface). – Remy Lebeau Mar 23 '17 at 17:40
  • in the A() , B() and A(). – GlacierSG Mar 23 '17 at 17:41
  • Ive just never seen this kind of code in c++. Is it often used? – GlacierSG Mar 23 '17 at 17:42
  • 1
    @JökullSnærGylfason: `A()` and `B()` are simply making copies of `std::string` objects. That memory is managed automatically, so there is no leaking. This type of chaining code is not *often* used, though a good example of it is STL I/O streams via `operator>>` and `operator<<` chaining, where a reference to the input stream is output in the return value. – Remy Lebeau Mar 23 '17 at 17:43
  • Okey. then its safe, thank you for the fast respond. I needed to be certain :) – GlacierSG Mar 23 '17 at 17:44
  • Related http://stackoverflow.com/questions/29429148/return-this-as-rvalue – Lol4t0 Mar 23 '17 at 18:18

1 Answers1

6

is return *this safe in c++

Fundamentally yes, it is safe. In fact, it is a common pattern. See: https://en.wikipedia.org/wiki/Method_chaining

Of course it can also be misused:

auto& foo = test().A("a");
foo.B("b"); // oops, foo is a dangling reference

my question is given this example:

[snip]

Is there going to be memory leakage?

No, there is no memory leakage in the shown code.

Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326