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. 

转载于:https://www.cnblogs.com/ruccsbingo/p/3805422.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值