我想知道从函数返回 *this 是否安全。 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;
}
会不会有内存泄漏?
最佳答案
is return
*this
safe in c++
基本上是的,它是安全的。事实上,这是一种常见的模式。请参阅:https://en.wikipedia.org/wiki/Method_chaining
当然也可以被误用:
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?
不,显示的代码中没有内存泄漏。
关于c++ - return *this 在 C++ 中安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42983174/