#include <iostream>#include <list>#include <algorithm>using namespace std;template <class T>void PRINT_ELEMENTS (const T& coll, const char* optcstr =""){typename T::const_iterator pos;std::cout << optcstr;for (pos=coll.begin(); pos!=coll.end(); ++pos) {std::cout << *pos << ' ';}std::cout << std::endl;}class IntSequence{private:int _value;public:IntSequence( int initialValue ) : _value( initialValue ){}int operator()( ){ return _value++; }int value(){ return _value; }};int main(){list< int > coll;IntSequence seq( 1 );generate_n< back_insert_iterator< list<int> >, int,IntSequence& >( back_inserter(coll), 4, seq ); // seq欲傳引用,改變seq._value的值PRINT_ELEMENTS( coll );generate_n( back_inserter(coll), 4, IntSequence(42) );PRINT_ELEMENTS( coll );generate_n( back_inserter(coll), 4, const_cast<IntSequence &>(seq) );PRINT_ELEMENTS( coll );generate_n( back_inserter(coll), 4, const_cast<IntSequence &>(seq) );PRINT_ELEMENTS( coll );}//在dev-cpp下輸出如下:1 2 3 41 2 3 4 42 43 44 451 2 3 4 42 43 44 45 5 6 7 81 2 3 4 42 43 44 45 5 6 7 8 5 6 7 8請按任意鍵繼續. . .//而在VS2010下輸出如下:1 2 3 41 2 3 4 42 43 44 451 2 3 4 42 43 44 45 1 2 3 41 2 3 4 42 43 44 45 1 2 3 4 1 2 3 4請按任意鍵繼續. . .
1 回答

森欄
TA貢獻1810條經驗 獲得超5個贊
你說的問題在VS2008上也是相同的表現,這個是因為微軟的庫實現不是直接實現在你call的generate_n這個函數上的,而是有好幾重轉調,所以造成你即使對第一重調用的 模板函數用 引用去實例化,由于后面轉調的函數都是使用值去實例化的,所以實際你得到的運行效果還是值語義的。
比如你call 函數 func1<A&>(), 但是由于func1<A&>() 調用了func2<A>(), 又繼續調用了func3<A>(), 最后func3里操作的其實是一個值拷貝,所以影響不到外面的引用的對象。
- 1 回答
- 0 關注
- 206 瀏覽
添加回答
舉報
0/150
提交
取消