简体   繁体   中英

Difference between Foo *foo; and Foo foo; in C++

I know the basics of pointers.

I would just like to know when you would use

Foo *foo; 

instead of

Foo foo;

and what one allows you to do that the other doesn't.

Thanks in advance

You typically use pointers if you want to refer to heap variables (object survives end of function), and the non-pointer form for local variables (lifetime ends with block/function).

As a member variable, you use pointers if you share Foo objects across different referrers, and you use embedded objects if you have a whole-part relationship with Foo.

If that's a variable declaration, Foo *foo; declares a variable of type pointer-to-Foo. Foo foo declares a variable of type Foo.

See wikipedia 's article on pointers for more info.

阅读针对该问题选择的答案非常直观: 理解指针的障碍是什么?如何克服这些障碍?

you use Foo * foo in many cases :

1 - if the returned value is an array of type Foo

2 - if the function manipulates some data structure (especially if you are working with a functional paradigm where the only result of a function is it's returned value) ex :

List * deleteListNode(int nbr, List * src) {
     Node * tmp = getElementPointer(nbr, src);
     tmp->prev->next = tmp->next;
     tmp->next->prev = tmp->prev;
     return src;
}

this function takes as arguments the number of an element in a list and a list and it return a pointer to the same list token as an argument after deleting the desired element, so the function does manipulate only pointer which as you know are 32 bits values (or maybe 64 bits on 64 bits systems).

3 - if the creation of the returned object is resource consuming so you would return a pointer to the existing object, especially in creation functions ex : List * createList , Tree * createTree ... because you do create your data structure inside the function so it is existing in the memory all you have to is to return it's address

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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