简体   繁体   English

关于函数返回指针

[英]Regarding function returning pointer

I want to clarify something about function returning pointer. 我想澄清一些有关函数返回指针的信息。

I understand pointer concept but in case of returning from function it is confusing me. 我理解指针的概念,但是如果从函数返回,这会使我感到困惑。

I learnt that when we want to return some data from function we write the type of data in return type for example in case of returning int type of data the return type will be int. 我了解到,当我们想从函数返回一些数据时,我们将数据类型写为return type,例如,如果返回的是int类型的数据,则返回类型将为int。

so when we want to return an address of some variable from a function we write return data type to be of some pointer type because memory address point to some sort of memory location that's why the return type is of pointer type what I want to clarify is that now this means that data type of addresses in c++ is of pointer type 因此,当我们要从函数返回某个变量的地址时,我们将返回数据类型写为某种​​指针类型,因为内存地址指向某种类型的内存位置,这就是为什么返回类型为指针类型的原因我想弄清楚的是现在这意味着c ++中地址的数据类型是指针类型

This how a general factory function works: 一般工厂功能的工作方式如下:

class HobNob;
...
HobNob* CreateHobNob()
{
    return new HobNob();
}
...
HobNob* myHobNob = CreateHobNob();

of course in real life we'd never use bare pointers, but the general idea is we need pointers because we don't want to be passing around HobNob s (which may be huge) but handles (pointers) to one created on the heap. 当然,在现实生活中,我们永远不会使用裸指针,但总的想法是我们需要指针,因为我们不想传递HobNob (可能很大),而是处理(指针)到在堆上创建的指针。 We can now also fully control its lifecycle. 现在,我们也可以完全控制其生命周期。

A function that returns a pointer looks something like this: 返回指针的函数如下所示:

int* foo()
{
    // some code
    return intPointer; // assuming intPointer is of type int*
}

or 要么

int* foo()
{
    // some code
    return new int; // return a newly created integer
}

If your function is supposed to create a new object of a type and return it. 如果您的函数应该创建一个新的类型的对象并返回它。

or 要么

int* foo()
{
    int* arr = new int[10]; // create an array dynamically
    // some code
    return arr; // return an array
}

If your function is supposed to return some array. 如果您的函数应该返回某个数组。

Obviously, you can change int with any data type you want. 显然,您可以使用所需的任何数据类型更改int

Also, as someone else pointed out it is not good idea to return the address of a local variable to outside of the function, so you would have to define the local variable as a static variable if you want to do that, otherwise it's undefined behaviour. 另外,正如其他人指出的那样,将局部变量的地址返回到函数外部也不是一个好主意,因此,如果要执行此操作,则必须将局部变量定义为静态变量,否则它是未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM