- 论坛徽章:
- 0
|
不好意思.实在不知道用什么合适的主题。
第一个疑问是STL标准模板库中的插入操作。
例如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]
- ......
复制代码 红色部分是我的疑问. 我发现insert中,都会对传入的插值引用建立一个局部拷贝,然后使用这份拷贝。而不使用传入的参数。
不知是何用意。如果是为了避免传入的__x被意外修改,这也说不通,因为__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;
- }
复制代码 将派生类使用static_cast转换为基类的引用,这样可以正确实现对基类成员的赋值。
原文:
- 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.
复制代码 如果是static_case<Base>(*this) = rhs;
这为何会引起调用Base的构造函数生成一个新的对象,并且赋值的对象是这个新对象?
我写了代码试了下,果然是这样。
各位大侠不吝赐教啊.
thx...
|
|