我99%确定答案是绝对的“不”。请验证我的主张,以下代码会产生内存泄漏。
请注意,这只是一个过于简化的示例,所以显然你不会实际使用上述代码...所以不需要指出谢谢。
更新1:
补充一下,如果我将指针分配给引用,那么情况怎么样?在这种情况下,我假设数据没有被复制...
产生以下结果...
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提供了精彩的回答(我在更新2中的代码是他示例代码的修改副本)。