使用对象,还是对象的指针

    To use an object or use a pointer is a question that we often encounter. This question often arises under the following circumstances:

A. parameters to the function

B. the return value of the function

C. to store something in the member variables or STL containers

    To decide which to use, we should clarify some basic concept first.  To use an object means that there must be a piece of memory storing the information associated with this object. And, note that there may be some copies of the object if you use an object under some circumstances. Conversely, the pointer occupies 4 byte in the memory which stores the address of the object. So there will be only one object and no copies will appear. But the address pointed by the pointer must make sense.

     Thus, we can find a rule that can judge whether to use : Do you mind using the copy of the object?  Sometimes,  there must one object in the memory that will make sense. For example, we often use GetDC to retrieve a handle to a display device context for the client area of a specified window. The return value is a pointer. As you see, there must be only one device context associated with that area. If the return value is designed as an object, there will a new object apart from the original object. That's unreasonable. Another typical example is to use the singleton pattern. It's obvious that there will be one object in the whole project, so the funtion designed to retrieve this object must return the pointer of that object.  Besides,  it's obvious that the operation to the copies will not affect the original object. That's why there is no effect after we take much operation sometimes.

     However, if you just need the value wrapped in the object,  you can use objects instead of pointers.  It doesn't matter even though there are many copies. Because you only need the value, and the copies have the same value with the original object.

     Thus it can be seen that it's important to know when the copy operation will happen. When you call a function,  the copy operation happens to the parameters and the return valuse. The STL containers all sotre copies of the object. 

     And here comes another rule. The copy of the object is a legal object anyway, while the pointer may not point to a validated object. So the rule is to make sure that the pointer points to a validated object. That's why not to return a pointer to temporary variables, since those objects will destruct at the end of the functions containing them.

    Another issue concerns the efficiency. In general, the copy operation will call the copy construct function. That will cost more.

    Well, which to use depends on the specific circumstances. Above is only for reference. 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值