﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>C++博客-时光隧道-文章分类-C++ Pitfalls</title><link>http://www.cppblog.com/thinke365/category/12173.html</link><description /><language>zh-cn</language><lastBuildDate>Mon, 26 Oct 2009 23:31:03 GMT</lastBuildDate><pubDate>Mon, 26 Oct 2009 23:31:03 GMT</pubDate><ttl>60</ttl><item><title>临时对象</title><link>http://www.cppblog.com/thinke365/articles/99542.html</link><dc:creator>thinke365</dc:creator><author>thinke365</author><pubDate>Mon, 26 Oct 2009 19:00:00 GMT</pubDate><guid>http://www.cppblog.com/thinke365/articles/99542.html</guid><wfw:comment>http://www.cppblog.com/thinke365/comments/99542.html</wfw:comment><comments>http://www.cppblog.com/thinke365/articles/99542.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/thinke365/comments/commentRss/99542.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/thinke365/services/trackbacks/99542.html</trackback:ping><description><![CDATA[<p>Type func() {<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;....<br>}<br>obj = func() // 该过程中会生成临时变量。<span style="FONT-SIZE: 10pt; COLOR: #0000ff">这个变量是由编译器生成的，没有显式地在C++代码中体现出来</span>。</p>
<p><span style="FONT-SIZE: 10pt; COLOR: #ff0000">除非特别注意，或者C++一直拿在手上，这些问题非常容易犯错</span>。<br><span style="FONT-SIZE: 10pt; COLOR: #0000ff">因为返回对象的生命周期在函数出去时已经结束，为了完成赋值，必须要拷贝复制一份到函数堆栈</span>。。。<br>这个临时对象不是命名对象。。。。<br><br>如果返回的是引用 &amp;，则不会生成新的对象。<br><br>另外一种临时对象则是更为诡异的，<span style="FONT-SIZE: 10pt; COLOR: #800080"><strong>下面的程序非但编译没有出错，居然还调用了构造函数生成临时对象</strong></span>。(<span style="FONT-SIZE: 10pt; COLOR: #ff0000">C++为了编译不出错，会尽可能查找合适的转换路径，以满足编译需要。</span>)<br>如下程序中，编译器就<span style="FONT-SIZE: 10pt; COLOR: #800080"><strong>自动生成了赋值操作符</strong></span>，类型转换，以及类型转换的中间结果。<br><br>#include &lt;iostream&gt;<br>using namespace std;</p>
<p>class Rational<br>{<br>public:<br>&nbsp;Rational(int a=0, int b=1) : m(a), n(b) {<br>&nbsp;&nbsp;cout &lt;&lt; "initailized..." &lt;&lt; endl;<br>&nbsp;}<br>private:<br>&nbsp;int m, n;<br>};</p>
<p>int main()<br>{<br>&nbsp;Rational r;<br>&nbsp;r = 100;&nbsp; // 居然没有编译出错<br>&nbsp;return 0;<br>}<br><br><br></p>
<img src ="http://www.cppblog.com/thinke365/aggbug/99542.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/thinke365/" target="_blank">thinke365</a> 2009-10-27 03:00 <a href="http://www.cppblog.com/thinke365/articles/99542.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>