如果我创建一个类,并将其对象放在一个函数*中。一旦函数结束了我创建的对象发生了什么?它会被删除吗?
编辑: *我从主
调用该函数答案 0 :(得分:5)
当您在代码块中声明变量时,该变量的生存期将持续到代码块结束。变量将在其生命周期结束时被销毁,即控制退出该块时。
这个名称的正确名称是自动存储持续时间,尽管有时是行话上的行话""使用。
如果你想保留变量中的值,那么你可以返回变量的副本(不用担心,编译器通常会对此进行优化)。
也可以使用手动管理的生命周期创建对象。在这种情况下,对象没有名称,您通过句柄管理它们,直到您在其句柄上调用delete
,它们的生命才会结束。
这种技术需要更多的关注,它比使用自动变量更复杂;我宁愿使用自动变量,除非你真的无法解决它们的问题。
答案 1 :(得分:2)
“会被删除吗?”
是。只要您使用自动存储持续时间(有时称为堆栈分配)创建该对象实例,它就会在超出范围时立即删除。
struct Foo {
Foo() {}
~Foo() {}
};
void bar() {
Foo foo1; // automatic storage duration
Foo* foo2 = new Foo(); // manually-managed lifetime
} // foo1 will be deleted here, while foo2 won't
答案 2 :(得分:-4)
它将被删除为本地范围的任何其他变量。当您创建其中一个时,它们将一直存在,直到函数结束,除非您创建指针。在这种情况下,数据在函数结束后仍然存在,但您可能会丢失引用。
class myClass{
int variable;
float etc;
}
void foo()
{
myClass foo1 = new myClass(); // creates new instance of myClass
// as it was declared inside the function it only local scope
myClass* foo2; // it is a pointer
*foo2 = foo1; // foo2 won't be deleted. The data will still be there
// However, if you loose the reference to it,
// you may not be able to access the data stored
}
int main()
{
// foo1 still does not exist
foo(); // foo1 is created and deleted inside foo()
// main still can't "see" foo1 because of its scope
// foo2 still exists - the memory has been alocated and has a copy of
// foo1 in it, but main can't access it because it does not have the
// reference to the memory address.
}
请注意,如果您在用于创建对象的内部使用其他功能,则无法访问该功能。