新的文章能用在RFE里吗?# Immigration - 落地生根
K*i
1 楼
某本数据结构英文教材上说Top方法是accessor, 返回值的时候栈中还有这个值,因此
可以返回const引用。Pop方法可以没有返回值,但带返回值的Pop方法不允许返回引用
,因为Pop后这个值逻辑上在栈中被删除了。
假如Top和Pop方法的原型是
template
const T& Top() const;
void Pop();
问题是Top方法返回引用也有问题:
如果调用者这样写
T t = S.Top();
这个问题不大,因为是赋值给t
但如果调用者这样写
const T& t = S.Top();
S.Pop();
这样一来,再使用t不就有问题了么?
可以返回const引用。Pop方法可以没有返回值,但带返回值的Pop方法不允许返回引用
,因为Pop后这个值逻辑上在栈中被删除了。
假如Top和Pop方法的原型是
template
const T& Top() const;
void Pop();
问题是Top方法返回引用也有问题:
如果调用者这样写
T t = S.Top();
这个问题不大,因为是赋值给t
但如果调用者这样写
const T& t = S.Top();
S.Pop();
这样一来,再使用t不就有问题了么?