`
bcyy
  • 浏览: 1824739 次
文章分类
社区版块
存档分类
最新评论

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
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics