References & the Copy-Constructor

1 There are certain rules when using references:    (Page 451)

A reference must be initialized when it is created. (Pointers can be initialized at any time.)

Once a reference is initialized to an object, it cannot be changed to refer to another object.  (Pointers can be pointed to another object at any time.)

You cannot have NULL references. You must always be able to assume that a reference is connected to a legitimate piece of storage.

 

2 References in functions     (Page 452)

When a reference is used as a function argument, any modification to the reference inside the function will cause changes to the argument outside the function.

 

3 Const references       (Page 453)

If you know the function will respect the constness of an object, making the arguement a const reference will allow the function to be used in all situations. For built-in types, the function will not modify the argument, and for user-defined types, the function will call only const member functions, and won't modify any public data members.

Temporary objects are always const, so if you donot use a const reference, that argument wonot be accepted by the compiler.

 

4 Argument-passing guidelines      (Page 455)

The efficiency savings can be substantial for such a simple habit: to pass an argument by value requires a constructor and destructor call, but if you are not going to modify the argument then passing by const refecence only needs an address pushed on the stack.

 

5 Copy-construction      (Page 463)

If you create a copy-construction, the compiler will not perform a bitcopy when creating a new object from an existing one. It always call your copy-constructor.

 

6 Temporary objects

 

7 Default copy-constructor

 

8 Alternatives to copy-construction

You need a copy-constructor only if you are going to pass an object of your class by value. If that never happens, you donot need a copy-constructor.

 

9 Preventing pass-by-value

There is a simple technique for preventing pass-by-value: declare a private copy-constructor. You donot even need to create  definition, unless one of your member functions or a friend function needs to perform a pass-by-value. If the user tries to pass or return the object by value, the compiler will produce an error message because the copy-constructor is private. 

posted @ 2014-06-24 09:36  ruccsbingo  阅读(247)  评论(0编辑  收藏  举报