网络服务器软件开发

C++博客 首页 新随笔 联系 聚合 管理
  84 Posts :: 3 Stories :: 50 Comments :: 0 Trackbacks

 

msdn上的解析:
value_type& front( ); 
const value_type& front( ) const;

Returns a reference to the first element at the front of the queue.

请看下面示例代码
queue<int> intqueue;
intqueue.push(1);
intqueue.push(2);
int head = intqueue.front();//int&可以隐式转换为int?
intqueue.pop();//将对头元素弹出队列
cout << head << endl;//输出1,front应该返回的是"引用",但pop之后,为什么head的输出还有效(引用还有效?)?

posted on 2008-06-10 11:39 true 阅读(487) 评论(3)  编辑 收藏 引用 所属分类: C++基础linux

Feedback

# re: std::queue的front的问题[未登录] 2008-06-10 12:39 cppexplore
value_type& front( );
只是说明返回的时候,不copy副本返回,直接返回私有属性本身。
比如:
class A
{
public:
A():a_(9){}
const int & get_a()const{return a_;}
private:
int a_;
};
int main()
{
A a;
printf("it's %d\n",a.get_a()+4);
return 0;
}
a.get_a()+4这个其实就是a_+4,而不设计到内存copy问题。如果get_a()前没有引用,则意味着先要把a_复制一副本,副本再和4相加。
该文中,int head=则是赋值操作,和后面的是否是引用无关,基本类型,当然会有效。  回复  更多评论
  

# re: std::queue的front的问题 2008-06-10 12:50 true
讲得很透彻,呵呵。以前经常这么用,但却不知道原理,看来是不理解引用  回复  更多评论
  

# re: std::queue的front的问题[未登录] 2008-06-12 13:26 tom
http://herbsutter.wordpress.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/  回复  更多评论
  


标题  
姓名  
主页
验证码 *
内容(提交失败后,可以通过“恢复上次提交”恢复刚刚提交的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
[使用Ctrl+Enter键可以直接提交]
相关链接:
网站导航: