#include <iostream>
#include <string>
usingnamespace std;
namespace passByReference
{
int a_function( string &s )
{
s = "Changed";
return 1;
}
}
namespace passByValue
{
int a_function( string s )
{
return 0;
}
}
int main()
{
// using namespace passByReference;
usingnamespace passByValue;
string s = "Hello";
int result = a_function( s );
cout << result << " " << s << '\n';
result = passByReference::a_function( s );
cout << result << " " << s << '\n';
}
0 Hello
1 Changed
Or you could limit scope (with same output as above)
The overloads that makes sense for me is one of the following:
1.
1 2
// modifies the string
int a_function(string& s)
2.
1 2
// reads the string
int a_function(const string& s)
3.
1 2 3 4
// same as #2 but copies the string internally and wants to optimize for the case when
// being passed an r-value reference (a temporary or the return from std::move).
int a_function(const string& s)
int a_function(string&& s)
4.
1 2
// Same as #3 but trades a small bit of performance for not having to implement two overloads.
int a_function(string s)
This ignores other types such as const char* and string_view that might also be used when passing strings.
Having both overload #1 and #4 does not make sense to me because they clearly do different things (one is modifying and one is reading) so they are not the same and should not have the same name.
#include <iostream>
#include <string>
int a_function( std::string& s ) // overload one
{
s = "Changed";
return 1;
}
int a_function( std::string ) // overload two
{
return 0;
}
int main()
{
std::string s = "Hello";
// overload one; resolves to (pointer to) overload one of the function
std::cout << ( (int(*)(std::string&))a_function )(s) <<'\n' ; // 1
// overload two (const; overload one is not a viable function)
std::cout << a_function( static_cast<const std::string&>(s) ) <<'\n' ; // 0
}