返回局部变量C ++的指针 [英] Returning a pointer of a local variable C++

查看:149
本文介绍了返回局部变量C ++的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个返回指向int的函数的函数。

I need to create a function that returns a pointer to an int.

像这样:

int * count()
{
    int myInt = 5;

    int * const p = &myInt;

    return p;
}

由于指针只是一个地址,变量myInt在此之后被销毁函数被调用。我如何声明一个int在这个方法中,将保​​持在内存中的一个地方,以便我以后通过返回的指针访问它?我知道我可以在函数之外声明这个int,但是我要在函数中声明它。

Since a pointer is simply an address, and the variable myInt is destroyed after this function is called. How do I declare an int inside this method that will keep a place in the memory in order for me to access it later via the returned pointer? I know I could declare the int globally outside of the function, but I want to declare it inside the function.

先感谢任何帮助!

推荐答案

使用新运算符

int * count()
{
    int myInt = 5;

    int * p = new int;
    *p = myInt;

    return p;
}

正如其他答案所指出的,这通常是一个坏主意。如果你必须这样做,那么也许你可以使用智能指针。查看这个问题如何做这个
什么是智能指针,我应该什么时候使用?

As pointed out in other answers this is generally a bad idea. If you must do it this way then maybe you can use a smart pointer. See this question for how to do this What is a smart pointer and when should I use one?

这篇关于返回局部变量C ++的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆