C++ 从函数返回类指针

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/773599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:13:06  来源:igfitidea点击:

Return class pointer from a function

c++

提问by theKing

I am not sure what is wrong with this (keep in mind I'm kinda sorta new to C++)

我不确定这有什么问题(请记住,我对 C++ 有点陌生)

I have this class:

我有这门课:

Foo
{
  string name;
  public:
     SetName(string);
}
string Foo::SetName(string name)
{
  this->name = name;
  return this->name;
};
//////////////////////////////////////////////
//This  is where I am trying to return a Foo pointer from this global function:

Foo * ReturnFooPointer()
{
  Foo foo;
  Foo * foo_ptr;
  foo_ptr = &foo;
  return foo_ptr;
}

At compile time, this compiles just fine. However at run time it throws a runtime exception(Some sort of access violation)

在编译时,这编译得很好。但是在运行时它会抛出一个运行时异常(某种访问冲突)

What am I doing wrong?

我究竟做错了什么?

回答by Brian R. Bondy

You need to use the new keyword instead to create new Foo on the heap.
The object on the stack will be freed when the function ends, so you are returning a pointer to an invalid place in memory.

您需要使用 new 关键字在堆上创建新的 Foo 。
当函数结束时,堆栈上的对象将被释放,因此您将返回一个指向内存中无效位置的指针。

Here is the correct code.

这是正确的代码。

Foo * ReturnFooPointer()
{
  Foo * foo_ptr = new Foo();
  return foo_ptr;
}

Remember later to delete the pointer you are returning.

记住稍后删除您正在返回的指针。

So later in code:

所以后面的代码:

Foo *pFoo = ReturnFooPointer();
//Use pFoo
//...
delete pFoo;

回答by Michael

You're returning a pointer to a local object on the stack. It goes out of scope the moment your function returns, and is invalid.

您正在返回指向堆栈上本地对象的指针。它在您的函数返回时超出范围,并且无效。

You should create a new instance to return, i.e.,

您应该创建一个新实例来返回,即,

Foo* foo_ptr = new Foo();

This will create an object in the heap and will live until you call deleteon it.

这将在堆中创建一个对象,并在您调用delete它之前一直存在。

回答by clawr

the actual object is allocated on the stack so it is destroyed when it goes out of scope (when the function returns). If you allocate it on the heap (with new), it will be alive until you deleteit

实际对象在堆栈上分配,因此当它超出范围时(当函数返回时)它会被销毁。如果你在堆上分配它(使用new),它会一直活着,直到你delete