C++ 这是用c+表示的保险箱吗+;?

C++ 这是用c+表示的保险箱吗+;?,c++,pointers,memory-leaks,C++,Pointers,Memory Leaks,我想知道从函数返回*这个是否安全。问题展示了一些方法,我的问题如下所示: 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() {

我想知道从函数返回*这个是否安全。问题展示了一些方法,我的问题如下所示:

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;
}
会有内存泄漏吗

return
*这在c中是否安全++

基本上是的,它是安全的。事实上,这是一种常见的模式。见:

当然,它也可能被误用:

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

我的问题是这样一个例子:

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;
}
[剪报]

会有内存泄漏吗


不,显示的代码中没有内存泄漏。

您认为哪些内存可能泄漏?为什么会有内存泄漏?我看不到任何分配和悬空指针。如果不请求任何内存,就不会泄漏内存。某些操作,如
运算符=
需要返回对
*this
的引用。所以是的,它是完全安全的。它是@JökullSnærGylfason的一种形式:
a()
B()
只是复制
std::string
对象。该内存是自动管理的,因此没有泄漏。这种类型的链接代码并不经常使用,尽管一个很好的例子是通过
操作符>
操作符的STL I/O流