hjk41的日志

Avatar

More Effective C++ 1: Distinguish between pointers and references

Main differences between pointers and references:
1. Pointers should be initialized while references must.
2. Pointers can be changed to point to a different object while references always refer to the same object.
3. References are used without "*"

1.


string * b;    // fine, you can initialize the pointer later
string & c;    // error! references must be initialized

string s("hello");
string & d=s;    // fine

2.


string a("this is a");
string b("this is b");
string * pa=&a;
string & ra=a;

pa=&b;    // now pa points to b, a is not changed
ra=b;    // now a="this is b"

3.


vector<int> v(10);
v[1]=10;    

// if you have the operator [] return a pointer, you will have to write this:
*v[1]=10;

评论已关闭