【发布时间】:2013-09-08 12:41:33
【问题描述】:
假设我有这个方法可以创建std::vector< std::string > 类型的对象
const std::vector< std::string > Database::getRecordNames() {
// Get the number of recors
int size = this -> getRecordCount();
// Create container
std::vector< std::string > names;
// Get some strings
for ( i = 0; i < size; i++ ) {
// Get a string
const std::string & name = this -> getName( i );
// Add to container
names.push_back( name );
}
// Return the names
return names;
}
然后在别的地方,我用这个方法
void Game::doSomething() {
const std::vector< std::string > & names = mDatabase -> getRecordNames();
// Do something about names
}
因此,在方法@987654326@ 上,它返回一个临时对象std::vector< std::string >。但是,在 Game::doSomething() 方法上,我将返回值放在了 const std::vector< std::string > & 类型的对象中。
这是不安全的,还是像这样使用它们完全正常? AFAIK,临时变量在其范围结束时被销毁。但是在我们的例子中,我们引用了这个临时变量,我相信它在返回值后会被销毁。
重写另一个方法是否更好,以便它使用返回值的副本而不是引用?
void Game::doSomething() {
const std::vector< std::string > names = mDatabase -> getRecordNames();
// Do something about names
}
【问题讨论】:
-
临时值被销毁...... except 当它们没有被销毁时。你所拥有的是例外,它是安全的。将临时值绑定到 const-reference 会将临时值的生命周期延长到引用变量的生命周期。
-
@KerrekSB 假设变量在
Game::doSomething()之后停止使用,它会自动销毁吗? -
@LanceGray:我的意思是我所说的:临时值的生命周期与其绑定的引用变量的生命周期相同。
标签: c++