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
  • 439
  • 4
  • 14

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
  • 223,800
  • 12
  • 181
  • 301