简体   繁体   English

为什么这段代码在C ++中有内存泄漏

[英]Why does this code have a memory leak in C++

I was told that the following code would result in a memory leak but I'm not certain why 我被告知以下代码会导致内存泄漏,但我不确定原因

object f(void)
    {
    object * o = new object(...);
    return *o;
    }

Is it because the object *o is copied before it is returned and the original copy is never deleted because it isn't an automatic variable? 是因为对象* o在返回之前被复制而原始副本永远不会被删除,因为它不是自动变量?

The object created by new is never delete d. new创建的对象永远不会delete d。

The returned value is a separate object that is copy-constructed from the object pointed to by o . 返回的值是一个单独的对象,它是从o指向的对象进行复制构造的。

In general, a function T f(){ /*...*/ return y; } 一般来说,函数T f(){ /*...*/ return y; } T f(){ /*...*/ return y; } creates its return value as if by T{y} , ie constructing a T with the argument y . 通过T{y} T f(){ /*...*/ return y; }创建其返回值,即使用参数y构造T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM