C++憤恨者札記8—— 常引用參數也不可靠的情況

#include <vector>
#include <string>
using namespace std;

//parameter 's' can only make sure reference value can't be modify according it, 
//but can't make sure other parameter, here is 'vec', change its reference value
//so the reference value of 's' may be change in Fn
void Fn( vector<string>& vec, const string& s )
{
	vec.erase( vec.begin() );
	vec.push_back( s );
}

void main()
{
	vector<string> vec;

	vec.push_back( "string1" );
	vec.push_back( "string2" );
	vec.push_back( "string3" );

	Fn( vec, vec[0] );	//vec after call Fn: string2, string3, string2
				//but not expected : string2, string3, string1
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章