Reputation: 85
Is it always safe to pass an empty or uninitialised STL container to a function by reference? e.g.
void some_function(deque<string> &passed_by_ref) {
passed_by_ref.push_back("a string");
}
int main() {
deque<string> some_data;
some_function(some_data);
return 0;
}
I haven't had any problems with this approach, but not sure if there could possibly be any NULL reference issues.
Upvotes: 0
Views: 346
Reputation: 55887
Yes, it's always safe. deque<T>
is not a pointer type - it's an object type. The standard containers have a default constructor, so, after this statement
deque<string> some_data;
some_data
is a correctly constructed empty deque
.
Upvotes: 3
Reputation: 59987
The line
deque<string> some_data;
ensures that the variable some_data
is at least initialised, as the constructor is called.
Therefore you are just passing a reference to an empty STL container - which is safe.
Upvotes: 1
Reputation: 24846
STL containers have default constructors, which are called in that case:
deque<string> some_data;
So the container is initialized and it's totally ok to pass a reference to it
Upvotes: 2