Quelles sont les différences entre une variable pointeur et une variable de référence en C+

Mots clés : c++pointersreferencec++-faqc++

meilleur 3 Réponses Quelles sont les différences entre une variable pointeur et une variable de référence en C+

vote vote

100

int x = 5; int y = 6; int *p; p = &x; p = &y; *p = 10; assert(x == 5); assert(y == 10); 
int x = 5; int y = 6; int &q; // error int &r = x; 
int x = 0; int &r = x; int *p = &x; int *p2 = &r;  assert(p == p2); // &x == &r assert(&p != &p2); 
int x = 0; int y = 0; int *p = &x; int *q = &y; int **pp = &p;  **pp = 2; pp = &q; // *pp is now q **pp = 4;  assert(y == 4); assert(x == 2); 
/* the code below is undefined; your compiler may optimise it  * differently, emit warnings, or outright refuse to compile it */  int &r = *static_cast<int *>(nullptr);  // prints "null" under GCC 10 std::cout     << (&r != nullptr         ? "not null" : "null")     << std::endl;  bool f(int &r) { return &r != nullptr; }  // prints "not null" under GCC 10 std::cout     << (f(*static_cast<int *>(nullptr))         ? "not null" : "null")     << std::endl; 
const int &x = int(12); // legal C++ int *y = &int(12); // illegal to take the address of a temporary. 
vote vote

88

std::string s1 = "123"; std::string s2 = "456";  std::string s3_copy = s1 + s2; const std::string& s3_reference = s1 + s2; 
vote vote

79

int * p = NULL; int & r = *p; r = 1;  // crash! (if you're lucky) 
class MyClass {     ...     virtual void DoSomething(int,int,int,int,int); };  void Foo(const MyClass & bar) {     ...     bar.DoSomething(i1,i2,i3,i4,i5);  // crash occurs here due to memory access violation - obvious why? }  MyClass * GetInstance() {     if (somecondition)         return NULL;     ... }  MyClass * p = GetInstance(); Foo(*p); 
template<typename T> T& deref(T* p) {     if (p == NULL)         throw std::invalid_argument(std::string("NULL reference"));     return *p; }  MyClass * p = GetInstance(); Foo(deref(p)); 

Questions similaires