Normally temporary objects such as the one created by the call to createF 5 are destroyed at the end of the expression. A compiler keeps "references" to variables, associating a name with a memory address; that's its job to translate any variable name to a memory address when compiling. When you create a reference, you only tell the compiler that you assign another name to the pointer variable; that's why references cannot "point to null", because a variable cannot be, and not be.
Pointers are variables; they contain the address of some other variable, or can be null. The important thing is that a pointer has a value, while a reference only has a variable that it is referencing.
Here you are not creating another variable that points to a ; you are just adding another name to the memory content holding the value of a. This memory now has two names, a and b , and it can be addressed using either name. When calling a function, the compiler usually generates memory spaces for the arguments to be copied to. The function signature defines the spaces that should be created and gives the name that should be used for these spaces.
Declaring a parameter as a reference just tells the compiler to use the input variable memory space instead of allocating a new memory space during the method call. It may seem strange to say that your function will be directly manipulating a variable declared in the calling scope, but remember that when executing compiled code, there is no more scope; there is just plain flat memory, and your function code could manipulate any variables. Now there may be some cases where your compiler may not be able to know the reference when compiling, like when using an extern variable.
So a reference may or may not be implemented as a pointer in the underlying code. But in the examples I gave you, it will most likely not be implemented with a pointer. There is a semantic difference that may appear esoteric if you are not familiar with studying computer languages in an abstract or even academic fashion. At the highest-level, the idea of references is that they are transparent "aliases".
Your computer may use an address to make them work, but you're not supposed to worry about that: you're supposed to think of them as "just another name" for an existing object and the syntax reflects that. They are stricter than pointers so your compiler can more reliably warn you when you about to create a dangling reference, than when you are about to create a dangling pointer.
Beyond that, there are of course some practical differences between pointers and references. The syntax to use them is obviously different, and you cannot "re-seat" references, have references to nothingness, or have pointers to references. While both references and pointers are used to indirectly access another value, there are two important differences between references and pointers.
The first is that a reference always refers to an object: It is an error to define a reference without initializing it. The behavior of assignment is the second important difference: Assigning to a reference changes the object to which the reference is bound; it does not rebind the reference to another object. Once initialized, a reference always refers to the same underlying object. After the assignment, ival, the object addressed by pi remains unchanged.
The assignment changes the value of pi, making it point to a different object. Now consider a similar program that assigns two references:. This assignment changes ival, the value referenced by ri, and not the reference itself. After the assignment, the two references still refer to their original objects, and the value of those objects is now the same as well.
A reference is an alias for another variable whereas a pointer holds the memory address of a variable. References are generally used as function parameters so that the passed object is not the copy but the object itself. It doesn't matter how much space it takes up since you can't actually see any side effect without executing code of whatever space it would take up. On the other hand, one major difference between references and pointers is that temporaries assigned to const references live until the const reference goes out of scope.
This is based on the tutorial. What is written makes it more clear:. What's more, as we can refer to almost any pointer tutorial, a pointer is an object that is supported by pointer arithmetic which makes pointer similar to an array. It is also OK to forget the terminology of such statement is to create a reference of Tom. Some specific instance of type that is not an object type. Some specific instance of type that is an object type.
An object type is a possibly cv -qualified type that is not a function type, not a reference type, and not cv void. Reference is also a top-level category.
But pointer is not. Pointers and references are mentioned together in the context of compound type. This is basically due to the nature of the declarator syntax inherited from and extended C, which has no references. So drafting a language specific by "extension" with similar style of C in this context is somewhat reasonable.
I will still argue that the syntax of declarators wastes the syntactic expressiveness a lot , makes both human users and implementations frustrating.
Thus, all of them are not qualified to be built-in in a new language design. This is a totally different topic about PL design, though. Otherwise, it is insignificant that pointers can be qualified as a specific sorts of types with references together. They simply share too few common properties besides the syntax similarity, so there is no need to put them together in most cases. Note the statements above only mentions "pointers" and "references" as types.
There are some interested questions about their instances like variables. There also come too many misconceptions. The differences of the top-level categories can already reveal many concrete differences not tied to pointers directly:. Technically, this is plain wrong. The statement above is simply wrong.
An object occupies a region of storage in its period of construction, throughout its lifetime, and in its period of destruction. Even that pointers are not qualified enough to be put together with references in the sense of the language design, there are still some arguments making it debatable to make choice between them in some other contexts, for example, when making choices on parameter types.
But this is not the whole story. I mean, there are more things than pointers vs references you have to consider. If you don't have to stick on such over-specific choices, in most cases the answer is short: you do not have the necessity to use pointers, so you don't. Pointers are usually bad enough because they imply too many things you don't expect and they will rely on too many implicit assumptions undermining the maintainability and even portability of the code.
Reconsider your purpose and you will finally find that pointer is the feature of last sorts in most cases. So, in practice, the answer is so obvious: when in doubt, avoid pointers. You have to use pointers only when there are very explicit reasons that nothing else is more appropriate. Such instances can be:. Other languages may or may not have similar restrictions on their references.
Java, C , There can still be some common properties among references in different programming languages in general, but let's leave it for some other questions in SO. A reference is not another name given to some memory. It's a immutable pointer that is automatically de-referenced on usage. Basically it boils down to:.
A reference to a pointer provides a cleaner syntax to modify the pointer. Look at this example:. And consider the C version of the above program. In C you have to use pointer to pointer multiple indirection , and it leads to confusion and the program may look complicated.
There is one fundamental difference between pointers and references that I didn't see anyone had mentioned: references enable pass-by-reference semantics in function arguments. Pointers, although it is not visible at first do not: they only provide pass-by-value semantics. This has been very nicely described in this article. Null pointers can be used as a sentinel value, often a cheap way to avoid function overloading or use of a bool.
At the risk of adding to confusion, I want to throw in some input, I'm sure it mostly depends on how the compiler implements references, but in the case of gcc the idea that a reference can only point to a variable on the stack is not actually correct, take this for example:. If you notice even the memory addresses are exactly the same, meaning the reference is successfully pointing to a variable on the heap!
Now if you really want to get freaky, this also works:. Well, obviously it compiles fine, but causes a segmentation fault at runtime because it's no longer pointing at a valid variable, we essentially have a broken reference that still exists until it falls out of scope , but is useless.
In other words, a reference is nothing but a pointer that has the pointer mechanics abstracted away, making it safer and easier to use no accidental pointer math, no mixing up '. Now regardless of how a compiler handles references, it will always have some kind of pointer under the hood, because a reference must refer to a specific variable at a specific memory address for it to work as expected, there is no getting around this hence the term 'reference'.
The only major rule that's important to remember with references is that they must be defined at the time of declaration with the exception of a reference in a header, in that case it must be defined in the constructor, after the object it's contained in is constructed it's too late to define it.
Remember, my examples above are just that, examples demonstrating what a reference is, you would never want to use a reference in those ways! For proper usage of a reference there are plenty of answers on here already that hit the nail on the head. Another difference is that you can have pointers to a void type and it means pointer to anything but references to void are forbidden.
I can't say I'm really happy with this particular difference. I would much prefer it would be allowed with the meaning reference to anything with an address and otherwise the same behavior for references. It would allow to define some equivalents of C library functions like memcpy using references. Also, a reference that is a parameter to a function that is inlined may be handled differently than a pointer.
Many compilers when inlining the pointer version one will actually force a write to memory we are taking the address explicitly. However, they will leave the reference in a register which is more optimal. Of course, for functions that are not inlined the pointer and reference generate the same code and it's always better to pass intrinsics by value than by reference if they are not modified and returned by the function.
This program might help in comprehending the answer of the question. This is a simple program of a reference "j" and a pointer "ptr" pointing to variable "x". Unlike the pointers, references are syntactically equivalent to the object they refer to, i.
Returning the character by reference allows user-defined classes to have the same notation. Copy constructors. Syntactically it makes sense to pass objects to copy constructors, and not pointers to objects.
But there is just no way for a copy constructor to take an object by value - it would result in a recursive call to the same copy constructor. This leaves references as the only option here.
Operator overloads. This also works for regular overloaded functions. Hence, it can be said that the changes done to a reference variable will also occur in variable referred by that reference variable.
The most important point is that the reference variable must be initialized at the time of its creation. Once the reference variable is initialized with a variable, it can not be reinitialized to refer an another variable. The moment you assign a value to a reference variable, you assign that value to a variable that a reference variable points to.
Arithmetic can not be performed on a reference variable. Note Java does not support pointers. The pointer and reference both are used to point or refer another variable. But both differ in their usage and implementation. Your email address will not be published. A reference variable can be said as another name for an existing variable.
Once this variable is initialized, the variable name can be used to refer to another variable. Pointers, on the other hand, are variables that store the address of a variable. References do not change an original variable, while if the pointer is changed, it affects the original variable. A reference must be initialized on the declaration, while it is not necessary to initialize a pointer once it is declared.
An array of pointers can be created, while an array of references cannot be created. A null value cannot be assigned to a reference, but it can be assigned to a pointer. Before using a pointer anywhere in the program, it should be declared in advance. A pointer is accompanied by the data type, which can be an int or a double. That address holds an int value. Reassignment A reference variable cannot be reassigned. These references can be passed to different functions; they can be stored in different classes, etc.
A reference never points to a new variable until the old one is deleted or goes out of scope. A pointer has its own memory address and stores it on the stack. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment? Please use ide. Load Comments. What's New. Most popular in C Language.
We use cookies to ensure you have the best browsing experience on our website.
0コメント