C++ Question

is return *this safe in c++?

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download