use*_*357 5 c++ pointers function
我需要创建一个返回指向int的指针的函数.
像这样:
int * count()
{
int myInt = 5;
int * const p = &myInt;
return p;
}
Run Code Online (Sandbox Code Playgroud)
由于指针只是一个地址,因此在调用此函数后,变量myInt将被销毁.如何在此方法中声明一个int,它将在内存中保留一个位置,以便我以后通过返回的指针访问它?我知道我可以在函数外部声明int,但是我想在函数内部声明它.
在此先感谢您的帮助!
使用new运算符
int * count()
{
int myInt = 5;
int * p = new int;
*p = myInt;
return p;
}
Run Code Online (Sandbox Code Playgroud)
正如其他答案所指出的,这通常是一个坏主意.如果你必须这样做,那么也许你可以使用智能指针.请参阅此问题以了解如何执行此操作 什么是智能指针以及何时应使用智能指针?
你可以使用智能指针.
例如:
unique_ptr<int> count()
{
unique_ptr<int> value(new int(5));
return value;
}
Run Code Online (Sandbox Code Playgroud)
然后您可以访问整数,如下所示:
cout << "Value is " << *count() << endl;
Run Code Online (Sandbox Code Playgroud)
你可以通过制作变量来做到这一点static
:
int* count()
{
static int myInt = 5;
return &myInt;
}
Run Code Online (Sandbox Code Playgroud)