Is return * this safe in C ++?
I was wondering if returning * from a function would be safe. this question shows how you can do this, and my question is in the following 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;
}
Will there be a memory leak?
+3
source to share
1 answer
returns
*this
safe in C ++
Basically, yes, it is safe. In fact, this is a common picture. See: https://en.wikipedia.org/wiki/Method_chaining
Of course, this could also be misused:
auto& foo = test().A("a");
foo.B("b"); // oops, foo is a dangling reference
my question is in the following example:
[cut]
Will there be a memory leak?
No, there is no memory leak in the shown code.
+5
source to share