Returning a pointer of a local variable C++(返回局部变量 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++ 的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回局部变量 C++ 的指针


基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04