C ++,在堆上创建的对象与本地对象-返回指针时 [英] c++, object created on the heap vs. local - when returning a pointer
问题描述
这是来自的后续问题 >在C#中安全而不在C ++中简单指针/引用的返回,
This is a follow up question from Safe in C# not in C++, simple return of pointer / reference,
这是
person* NewPerson(void)
{
person p;
/* ... */
return &p; //return pointer to person.
}
和?
person* NewPerson(void)
{
person* pp = new person;
return pp; //return pointer to person.
}
我知道第一个是一个坏主意,因为它将是一个疯狂的指针. 在第二种情况下,对象在堆上是否安全-就像在C#中一样 上次引用到达时超出范围了吗?
I know that the first one is a bad idea, because it will be a wild pointer. In the second case, will the object be safe on the heap - and like in c# go out of scope when the last reference is gone to it?
推荐答案
这是安全的,返回后该对象仍将保持活动状态.
It's safe, the object will still be alive after the return.
但是不要期望在C ++中为您自动清除对象.标准C ++没有垃圾回收.您需要自己delete
该对象,或使用某种形式的智能指针.
But don't expect the object to be automatically cleaned up for you in C++. Standard C++ does not have garbage collection. You'll need to delete
the object yourself, or use some form of smart pointer.
这篇关于C ++,在堆上创建的对象与本地对象-返回指针时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!