Given prototypes:
void foo(int i);
void foo(int i, const std::string &s);
Implementation:
void foo(int i)
{
foo(i, std::string()) ;
//! ^^^^^^^^^^^^^ ^ here?
// nothing more.
}
//! ^ here?
void foo(int i, const std::string &s)
{
//do something
}
Where does the temporary object created by std::string()
go out of scope? Is it a good practise to overload functions this way?
Update:
Let me explain a little bit of the situation. As an exercise, I'm trying to write a class like a std::vector
without using a template. The only type it holds is std::string
. The class body can be found in another question.
When implementing the resize()
member function, I found that std::vector
seems are using two functions:
void
resize(size_type __new_size);
void
resize(size_type __new_size, const value_type& __x);
So I'm wondering whether I should use two functions instead of a single one.
I don't think it's bad practice, especially if you make foo(int i)
inline. I can think of a reason when this is preferred: when you create pointers to function, if you declare the second parameter default, you can have only pointer to function that accepts 2 parameters.
The temporary value is alive only as the parameter for the function call.
inline void foo(int i)
{
foo(i, std::string());
}
void foo(int i, const std::string &s)
{
//do something
}