网络服务器软件开发/中间件开发,关注ACE/ICE/boost

C++博客 首页 新随笔 联系 聚合 管理
  152 Posts :: 3 Stories :: 172 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 阅读(2608) 评论(2)  编辑 收藏 引用 所属分类: 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的问题[未登录] 2013-12-19 12:35 星爷
在c++中int并不是类,没有析构,是值拷贝。
你换std::string试试,准挂。  回复  更多评论
  


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理