1. 程式人生 > >What are the differences between a pointer variable and a reference variable in C++?

What are the differences between a pointer variable and a reference variable in C++?

Question:

I know references are syntactic sugar, so code is easier to read and write.

But what are the differences?

Summary from answers and links below:

  1. A pointer can be re-assigned any number of times while a reference can not be re-seated after binding.
  2. Pointers can point nowhere (NULL), whereas reference always refer to an object.
  3. You can't take the address of a reference like you can with pointers.
  4. There's no "reference arithmetics" (but you can take the address of an object pointed by a reference and do pointer arithmetics on it as in &obj + 5).

To clarify a misconception:

The C++ standard is very careful to avoid dictating how a compiler must implement references, but every C++ compiler implements references as pointers. That is, a declaration such as:

int&ri = i;

if it's not optimized away entirelyallocates the same amount of storage as a pointer, and places the address of i into that storage.

So, a pointer and a reference both occupy the same amount of memory.

As a general rule,

  • Use references in function parameters and return types to define useful and self-documenting interfaces.
  • Use pointers to implement algorithms and data structures.

Interesting read:

Answer:
  1. A pointer can be re-assigned:

    int x =5;int y =6;int*p;
    p =&x;
    p =&y;*p =10;
    assert(x ==5);
    assert(y ==10);

    A reference cannot, and must be assigned at initialization:

    int x =5;int y =6;int&r = x;
  2. A pointer has its own memory address and size on the stack (4 bytes on x86), whereas a reference shares the same memory address (with the original variable) but also takes up some space on the stack. Since a reference has the same address as the original variable itself, it is safe to think of a reference as another name for the same variable. Note: What a pointer points to can be on the stack or heap. Ditto a reference. My claim in this statement is not that a pointer must point to the stack. A pointer is just a variable that holds a memory address. This variable is on the stack. Since a reference has its own space on the stack, and since the address is the same as the variable it references. More on stack vs heap. This implies that there is a real address of a reference that the compiler will not tell you.

    int x =0;int&r = x;int*p =&x;int*p2 =&r;
    assert(p == p2);
  3. You can have pointers to pointers to pointers offering extra levels of indirection. Whereas references only offer one level of indirection.

    int x =0;int y =0;int*p =&x;int*q =&y;int**pp =&p;
    pp =&q;//*pp = q**pp =4;
    assert(y ==4);
    assert(x ==0);
  4. Pointer can be assigned NULL directly, whereas reference cannot. If you try hard enough, and you know how, you can make the address of a reference NULL. Likewise, if you try hard enough you can have a reference to a pointer, and then that reference can contain NULL.

    int*p = NULL;int&r = NULL;<--- compiling error
  5. Pointers can iterate over an array, you can use ++ to go to the next item that a pointer is pointing to, and + 4 to go to the 5th element. This is no matter what size the object is that the pointer points to.

  6. A pointer needs to be dereferenced with * to access the memory location it points to, whereas a reference can be used directly. A pointer to a class/struct uses -> to access it's members whereas a reference uses a ..

  7. A pointer is a variable that holds a memory address. Regardless of how a reference is implemented, a reference has the same memory address as the item it references.

  8. References cannot be stuffed into an array, whereas pointers can be (Mentioned by user @litb)

  9. Const references can be bound to temporaries. Pointers cannot (not without some indirection):

    constint&x =int(12);//legal C++int*y =&int(12);//illegal to dereference a temporary.

    This makes const& safer for use in argument lists and so forth.


相關推薦

What are the differences between a pointer variable and a reference variable in C++?

Question: I know references are syntactic sugar, so code is easier to read and write. But what are the differences? Summary from answ

Ask HN: What are the “best” logging practices to learn for a Junior Developer?

A short while ago I read in the comment section of an article here on HN regarding things to ask before joining a startup as a developer. The article itsel

What is the difference between arm-linux-gcc and arm-none-linux-gnueabi and arm-linux-gnueabi toolch

Toolchains have a loose name convention like arch[-vendor][-os]-abi. arch is for architecture: arm, mips, x86, i686... vendor is t

What Are The Great Things About Purchasing A Computerized Brick Making Machine?

Stop to get a minute and take into consideration all of the different techniques that concrete bricks and blocks are being used inside the constru

The differences between a login shell and interactive shell?

An interactive shell is one started without non-option arguments, unless -s is specified, without specifying the -c option, and wh

What's the difference between a stub and mock?

I believe the biggest distinction is that a stub you have already written with predetermined behavior. So you would have a class that implements the depend

Ask HN: What are the absolute essentials to become a software developer

I am a mathematician who wants to get into software development. What are the absolute essentials bits to know from theory, application and coding guidelin

What is the difference between a chatbot and a virtual assistant?

Use of cookies: We our own and third-party cookies to personalise our services and collect statistical information. If you continue browsing the site, you

What is the difference between Kill and Kill -9 command in Unix?

data esp osi lin mil print ren win sku w difference kill -9 pid and kill pid command - Ask Ubuntu https://askubuntu.com/questions/7918

並發與並行的區別 The differences between Concurrency and Parallel

並發與並行 mark 並行執行 程序 log tween 計算 線程 currency 邏輯控制流 在程序加載到內存並執行的時候(進程),操作系統會通過讓它和其他進程分時段占用CPU(CPU slices)讓它產生自己獨占CPU的假象(同時通過虛擬內存讓它產生獨占內存的假

【轉載】What is the difference between authorized_keys and known_hosts file for SSH?

led accounts dep protocol wide HERE data round enc The known_hosts file lets the client authenticate the server, to check that it isn‘t c

[轉]what’s the difference between @Component ,@Repository & @Service annotations in Spring

fir 結合 invoke doc repo supported rest 持久 can 原文地址:https://www.cnblogs.com/softidea/p/6070314.html @Component is equivalent to <bean&

What is the difference between static func and class func in Swift?

truct computed per value subclass guid between tab odi Special Kinds of Methods Methods associated with a type rather than an instance

What is the difference between iface eth0 inet manual and iface eth0 inet static?

iface eth0 inet static: Defines a static IP address for eth0 iface eth0 inet manual :To create a network interface without an IP address at a

What is the difference between book depreciation and tax depreciation?

  Generally, the difference involves the "timing" of the depreciation expense on a company's financial statementsversus the depreciati

[C/C++]The differences between #ifndef & #pragma once

#ifndef CLASSNAME_H #define CLASSNAME_H #endif This method can not solve the problem that once two classname is the same,then both of the class wit

What is the difference between PPTP, L2TP/IPsec, SSTP, IKEv2, and OpenVPN?

相關文章: iOS10把PPTP協定拿掉了,VPN協定只剩下L2TP、IPSEC、IKEv2。IKEv2 從 iOS 8.0 版開始支援。 PPTP和L2TP都使用PPP協議對資料進行封裝,然後新增附加包頭用於資料在網際網路絡上的傳輸。儘管兩個協議非常相似,但是仍存在以下幾方面的不同: 1.PPT

Ask HN: What's the best supply chain management software for a small businesses?

I'm currently researching on multiple options to manage the supply chain for my business : http://tarunaturals.com/

Ask HN: What are the best gamified education systems you are aware of?

I am looking for non-traditional education systems such as video games, VR immersion or some other types that help teach concepts - paid or free.

Ask HN: What are the most enjoyable REST APIs you've used?

I want to take a look at some great REST APIs as a reference. I'm looking to see how stuff like authorization, querying, filters have been implemented etc.