在c ++中返回*这是安全的吗?

Gla*_*r11 4 c++ pointers memory-leaks

我想知道从函数返回*this是否安全.这个问题显示了一些你可以做到的方法,我的问题是这个例子:

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;
}
Run Code Online (Sandbox Code Playgroud)

是否会出现内存泄漏?

eer*_*ika 6

*this在c ++中是安全的

从根本上说是的,这是安全的.实际上,这是一种常见的模式.请参阅:https://en.wikipedia.org/wiki/Method_chaining

当然它也可能被滥用:

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

我的问题是这个例子:

[剪断]

是否会出现内存泄漏?

不,所示代码中没有内存泄漏.