c++ - return *this 在 C++ 中安全吗?

标签 c++ pointers memory-leaks

我想知道从函数返回 *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/

相关文章:

c++ - const引用类型的模板类型推导

c++ - std::stringstream 缓冲区操作

c++ - Xcode 初学者需要帮助开始调试

c++ - 插入迭代器 vs 容器的成员函数插入器

python - 在python中通过网络发送函数指针

c - 指针取消引用如何工作?

javascript - 如何在用 React 编写的应用程序中查找内存泄漏

php - 为什么我在使用 $item->get_permalink() 时会在 SimplePie 中发生内存泄漏?

c - 给菜鸟的C语言指针

c# - 实体数据查询和内存泄漏