- 論壇徽章:
- 0
|
不好意思.實(shí)在不知道用什么合適的主題。
第一個疑問是STL標(biāo)準(zhǔn)模板庫中的插入操作。
例如deque中的一個。- template <class _Tp, class _Alloc>
- typename deque<_Tp, _Alloc>::iterator
- deque<_Tp,_Alloc>::_M_insert_aux(iterator __pos, const value_type& __x)
- {
- difference_type __index = __pos - _M_start;
- [b][color=Red]value_type __x_copy = __x;[/color][/b]
- ......
復(fù)制代碼 紅色部分是我的疑問. 我發(fā)現(xiàn)insert中,都會對傳入的插值引用建立一個局部拷貝,然后使用這份拷貝。而不使用傳入的參數(shù)。
不知是何用意。如果是為了避免傳入的__x被意外修改,這也說不通,因?yàn)開_x是const引用。
第二個疑問是來自effective C++中的,見Item 16.
他個的例子代碼是
- Derived& Derived::operator=(const Derived& rhs)
- {
- if (this == &rhs) return *this;
- static_cast<Base&>(*this) = rhs; // call operator= on
- // Base part of *this
- y = rhs.y;
- return *this;
- }
復(fù)制代碼 將派生類使用static_cast轉(zhuǎn)換為基類的引用,這樣可以正確實(shí)現(xiàn)對基類成員的賦值。
原文:
- Careful now! It is important that the cast be to
- a reference to a Base object, not to a Base object itself. If you cast *this to be a Base object, you'll end up
- calling the copy constructor for Base, and the new object you construct (see Item M19) will be the target of the
- assignment; *this will remain unchanged. Hardly what you want.
復(fù)制代碼 如果是static_case<Base>(*this) = rhs;
這為何會引起調(diào)用Base的構(gòu)造函數(shù)生成一個新的對象,并且賦值的對象是這個新對象?
我寫了代碼試了下,果然是這樣。
各位大俠不吝賜教啊.
thx...
|
|