《Effective C++》条款26

尽可能延后变量定义式的出现时间

string test(const string& passwd)
{
	string s;
	if (s.size() < MinLenth)
	{
		throw logic_error("passwd is too short");
	}
}

这段代码的问题是:如果抛出了异常,那么定义的string对象将面临毫无意义的构造和析构。

所以可以这样修改:

string test(const string& passwd)
{
	
	if (s.size() < MinLenth)
	{
		throw logic_error("passwd is too short");
	}
	string s;
	...
	return s;
}

但是这段代码仍然不够秾纤合度,因为s虽获定义却无任何实参作为初值。这意味调用的是其default构造函数。许多时候你该对对象做的第一次事就是给它个值,通常是通过一个赋值动作达成。

更受欢迎的是以passwd作为s的初值,跳过毫无意义的default构造过程。

string test(const string& passwd)
{
	
	if (s.size() < MinLenth)
	{
		throw logic_error("passwd is too short");
	}
	...
	string s(passwd);
	...
}

你不只应该延后变量的定义,直到非得使用该变量的前一刻为止,甚至应该尝试延后这份定义直到能够给它初值实参为止。如果这样, 不仅能够避免构造和析构非必要对象,还可以避免毫无意义的default构造行为。

你可能感兴趣的:(c++)