gpt4 book ai didi

c++ - 分配给 new 的内存是否会自动释放?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:48:39 26 4
gpt4 key购买 nike

我 99% 确定答案是盲目的。请验证我的以下代码会产生内存泄漏的命题。

Data &getData()
{
Data *i = new Data();
return *i;
}

void exampleFunc()
{
Data d1 = getData();
Data d2;

/* d1 is not deallocated because it is on the heap, and d2 is
* because it is on the stack. */
}

请注意,这是一个过于简化的示例,很明显您实际上不会使用上面的代码...因此无需指出这一点,谢谢。

更新 1:

除此之外,如果我将指针分配给一个引用会怎么样?在这种情况下,我假设数据未被复制...

Data &getData()
{
Data *i = new Data();
return *i;
}

void exampleFunc()
{
// Does copying occur here?
Data &d1 = getData();

// Does this deallocate the memory assigned to the pointer?
delete &d;
}

更新 2:

我想回答我自己的问题(在更新 1 中),以下代码证明将引用分配给引用不会导致复制...

#include <iostream>
#include <string>

using namespace std;

class Data
{
public:
string mName;

Data(const string &name) : mName(name)
{ cout << mName << " default ctor" << endl; }

Data(const Data& other)
{
mName = other.mName + " (copy)";
cout << mName << " copy ctor" << endl;
}

~Data()
{ cout << mName << " dtor" << endl; }

static Data &getData(const string &name)
{
Data *d = new Data(name);
return *d;
}
};

int main()
{
cout << "d1..." << endl;
Data d1 = Data::getData("d1");

cout << "d2..." << endl;
Data d2("d2");

cout << "d3..." << endl;
Data &d3 = Data::getData("d3");

cout << "return..." << endl;
return 0;
}

产生以下结果...

d1...
d1 default ctor
d1 (copy) copy ctor
d2...
d2 default ctor
d3...
d3 default ctor
return...
d2 dtor
d1 (copy) dtor

感谢 Eric Melski a great answer (我在更新 2 中的代码是他的示例代码的修改拷贝)。

最佳答案

实际上 d1d2 都会被释放,因为它们都在栈上。未释放的是您在 getData() 函数中分配的 Data 对象。如果在构造函数和析构函数中使用检测来充实 Data 类,您可以更清楚地看到这一点。例如:

class Data {
public:
Data() { cout << "Data default ctor" << endl; }
Data(const Data& other) { cout << "Data copy ctor" << endl; }
~Data() { cout << "Data dtor" << endl; }

static Data& getData()
{
Data *i = new Data();
return *i;
}
};

请注意,我已经明确声明了Data 的复制构造函数。在您的示例中,您在执行 Data d1 = getData(); 时隐式调用了该构造函数,我怀疑这就是您的困惑所在。现在,如果我运行这个简单的程序:

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
Data d1 = Data::getData();
Data d2;

return 0;
}

输出如下:

Data default ctor
Data copy ctor
Data default ctor
Data dtor
Data dtor

逐行,这是您所看到的:

  1. 当您在 getData() 中分配新的 Data 时,将调用默认构造函数。
  2. 调用复制构造函数以从您刚刚创建的动态分配的 Data 中创建 d1
  3. 调用默认构造函数来创建 d2
  4. d2 的析构函数在 main() 结束时超出范围时被调用。
  5. d1 的析构函数在 main() 结束时超出范围时被调用。

请注意,有三个构造函数调用,但只有两个析构函数调用——表明您恰好泄漏了一个 Data 对象。

希望对你有帮助,

埃里克梅尔斯基

关于c++ - 分配给 new 的内存是否会自动释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/765971/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com