Say I have this method that creates an object of type 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;
}
And then somewhere else, I use this method
void Game::doSomething() {
const std::vector< std::string > & names = mDatabase -> getRecordNames();
// Do something about names
}
So, on the method Database::getRecordNames()
, it returns a temporary object std::vector< std::string >
. However, on the method Game::doSomething()
, I placed the return value to a const std::vector< std::string > &
-type object.
Is this unsafe, or is it perfectly normal to use them like this? AFAIK, temporary variables are destroyed on the end of their scope. But in our case, we reference this temporary variable, in which I believe will be destroyed after it returns the value.
Is it better to rewrite the other method so that it would use a copy of the returned value instead of a reference?
void Game::doSomething() {
const std::vector< std::string > names = mDatabase -> getRecordNames();
// Do something about names
}