Given these 2 functions that modify and return a string:
// modify the original string, and for convenience return a reference to it
std::string &modify( std::string &str )
{
// ...do something here to modify the string...
return str;
}
// make a copy of the string before modifying it
std::string modify( const std::string &str )
{
std::string s( str );
return modify( s ); // could this not call the "const" version again?
}
This code works for me using GCC g++, but I don't understand why/how. I'd be worried that 2nd function would call itself, leaving me with out-of-control recursion until the stack is exhausted. Is this guaranteed to work?
You have two overloaded functions:
std::string &modify( std::string &str )
std::string modify( const std::string &str )
What you're passing is a non const-qualified std::string. Therefore, the function that takes the non const-qualified argument is a better fit. If that didn't exist, the compiler could convert the non const-qualified string to a const-qualified string to make the call, but for function overloading a call that requires no conversion is a better fit than a call that requires a conversion.
return modify( s ); // could this not call the "const" version again?
No. It is not recursion. It would invoke the other overload whose parameter is std::string &.
It is because the type of the expression s is std::string & which matches with the parameter type of the other overloaded function.
In order to recurse, the argument at call-site needs to convert into std::string const &. But in your case, this conversion is unnecessary as there exists an overload which doesn't require conversion.
This isn't recursion, it's overloading. When you call the second function, the argument going into it is a constant string. Inside that function, you call the other function which takes a non-const string. What you're doing is stripping the const-ness of the string and a better way of doing that would be to use const_cast.
I'll just link to this other stackoverflow thread.
Related
I am trying to push a string in a string vector, like below
void Node::set_val(string &val)
{
this->val.push_back(val);
}
But when I try to call it as below
Obj.set_val("10h;");
I get the below error,
error: no matching function for call to 'Node::set_val(const char [5])'
I assumed that the string in " " is same as string in c++, Why do I get such an error? What has to be changed below?
You are taking in a std::string by non-const reference. Non-const references cannot bind to rvalues, like "10h;", so you can't pass literals in to that function.
If you aren't going to modify the argument, you should take your argument by reference-to-const:
void Node::set_val(const string &val)
// ^^^^^
This way, a temporary std::string will be constructed from your const char[5] and passed in to set_val.
You could improve this by taking in the string by value and moveing it into the vector:
void Node::set_val(string val)
{
this->val.push_back(std::move(val));
}
This prevents you from making some unnecessary copies.
So in C++, const char* is implicitly convertible to std::string because std::string has a (non-explicit) constructor that takes const char*. So what the compiler tries here is to create a temporary std::string object for your function call, like so:
Node.set_val(std::string("10h;"));
However, since you declared the parameter of set_val to be a non-const reference to a std::string, the compiler can't make this conversion work due to the fact that temporary objects can't be bound to non-const references.
There are three ways to make this work, depending on what you want to achieve:
void Node::set_val(const std::string& val) {}
void Node::set_val(std::string val) {}
void Node::set_val(std::string&& val) {}
All will compile (the last one requires C++11 or higher), but seeing your use case, I would recommend to use the second or third one. For an explanation why, try reading a little bit about move semantics in C++11.
The important thing to take away here is that const char* implicitly converts to std::string by creating a temporary object, and temporary objects can't be passed to functions taking non-const references.
You are passing "10h;" which is a const char array.
Fix it by passing a string: Obj.set_val(string("10h")); and edit function to take a string by value:
void Node::set_val(string val) { /* */ }
Or maybe better, edit your function to take a const string&:
void Node::set_val(const string &val) { /* */ }
I have a function defined as:
void func(string & str_alias)
{...}
And in my main function
int main()
{
string a;
func((a="Cat said: ")+"Meow");
}
The compiler would report that
no known conversion for argument 1 from ‘std::basic_string<char>’ to ‘std::string& {aka std::basic_string<char>&}’
Though I know if I change the main function into:
int main()
{
string a;
func(a=((a="Cat said: ")+"Meow"));
}
The code would pass with no issues. But I still wonder why the returned string cannot be passed to the function as a reference. Why do I have to assign it to another string variable?
Thanks.
As long you don't need to change the passed reference, you could easily avoid this by changing your function signature to
void func(const string & str_alias)
// ^^^^^
{...}
and simply call
func(string("Cat said: ") + "Meow");
(see live demo)
If you'll need to change the reference parameter, you must have an lvalue to be modified. Nevertheless writing
func(a=string("Cat said: ")+"Meow");
is sufficient (see the live demo).
If you make it take const reference to std::string, it should compile.
This is because the last thing you do in the first function call is calling std::string operator+(const std::string&, const char*), which as you see returns std::string, not reference, and since it not stored anywhere, it is rvalue, which can't be bound to lvalue-reference.
The second example compiles, because the last thing you do is assign it to the variable a, which calls std::string& operator=(const char*), which as you can see returns reference, so it can be used as non-const reference by itself.
Thanks to 0x499602D2 for correction.
Let's say I have function foo(string& s). If I would get C string, foo(char* s), I would simply call the function as foo("bar").
I wonder if I can somehow do it in the C++ String?
Somehow to shorten this:
string v("bar");
foo(v)
I'm using Linux GCC C++.
It is not working because the argument has to be a const reference:
void foo( const std::string& s )
// ^^^^^
foo( "bar" ); // will work now
If you want foo to only read from the argument you should write foo(const string& s).
If you want foo to save the string somewhere (a class member..) you should write foo(string s).
Both versions allow you to write foo("bar"); which would't make any sense with a non const reference.
You could also try foo(string("bar")); to get your desired results, but since it is expecting a reference this wont work either.
So that means that your best bet is overloading for const char * to call the string method (this way you maintain only one method).
The std::string class does have an implicit conversion from const char*, so normally, passing a string literal into a function taking std::string works just fine.
Why it fails in your case is that the function takes its parameter as a non-const lvalue reference, and thus it requires an actual std::string lvalue to operate on.
If the function actually wants to take a non-const lvalue reference (i.e. it modifies the argument), you have to create an lvalue std::string and pass it (just like you do).
If the function does not modify the argument, change it to take by const-reference (const std::string&) or by value (std::string) instead; for both of these, passing an rvalue (like the std::string created by implicit conversion from const char*) will work and you can thus call the function with string literals.
The code below:
void test(string &s){ // if the argument is "string s", it works
return test(s+',');
}
The compiler reports cannot find the function: test(std::basic_string).
I think the compiler would create a temporary string (== s+','), and I can pass its reference.
But it seems I am wrong. I do not know why I cannot pass the reference of this temporary string.
You can't bind a temporary to a non-constant reference. You could either take the argument by const reference (or, as you point out, by value)
void test(string const & s){ // or string s
return test(s+',');
}
or use a named variable rather than a temporary
void test(string & s){
std::string s2 = s + ',';
return test(s2);
}
As noted, at great length, in the comments, this code has undefined runtime behaviour and shouldn't be used in "real" code; it's purpose is just a minimal example of how to fix the observed compilation error
make it const:
void test(const std::string &s){ // if the argument is "string s", it works
return test(s+',');
}
But first you should have seen this question String Concatenation
concatenating strings using "+" in c++
Alternative Solution
void test(string &s)
{
s.append(",");
return test(s);
}
Standard C++ does not allow a non-const lvalue reference to be bound to an rvalue. In your example, the result of the expression s+',' is a temporary and thus an rvalue, so the compiler is required to discard the overload of test expecting an lvalue reference, leaving it no overload available to call. That's why it complains about not being able to find the function test.
To solve this issue you have to provide an overload whose parameter may be bound to an rvalue. As you realized yourself, expecting an argument by-copy works, but it may imply unnecessary overhead by calling copy/move-ctors. A better option would be to expect the argument by reference. Since const lvalue references may be bound to rvalues, declaring the function as follows solves the problem.
void test(std::string const& s)
My function declaration is
siteObject(std::string& url, std::string& get, std::string& post);
So why is this site("String 1", "String 2", "String 3"); creating a mismatch type error. It says it wants a string reference and it's receiving a char array. If you need more detail just ask in the comments.
Because there's an implicit call to the std::string constructor, which creates a temporary object. You cannot take a non-const reference to a temporary (because it's meaningless to modify a temporary).
So, either modify your function to take const references, or by-value, or pass it non-temporary objects.
Your siteObject function:
siteObject(std::string& url, std::string& get, std::string& post);
takes non-const references to string objects, which cannot be bound to rvalues (or temporaries).
When you try to call the function with string literals, the compiler has to convert those arguments (which are char*) to something that matches the parameter types - that conversion results in a temporary std::string object.
You'll need to change your function to accept const references if you want to be able to bind them to temporaries:
siteObject(std::string const& url, std::string const& get, std::string const& post);
Or you could pass values instead of references:
siteObject(std::string url, std::string get, std::string post);
You need to either make your function accept const std::string& str or construct string instances to pass in, and not rely on the implicit conversion of char* to string objects.
The correct call is:
std::string url("...");
std::string get("...");
std::string post("...");
siteObject(url, get, post);
This makes sense since the method signature implies that you get something back in the three strings (non-const references) and you may use those return values.
If that's not the intention and you have the ability to change the siteObject() method then you should do:
siteObject(std::string const & url, std::string const & get, std::string const & post);
and use your original call.
Strings entered in double quote characters are coming from the C heritage of C++ (they are called C string or NUL terminated string). They are implemented by the compiler as array of char. On the contrary, the std::string is a C++ class that aims to simplify manipulation of strings. It owns a C string (and can be created from one since it has a constructor that accept a const char*), and manage its memory.
Since there exists a construtor of std::string from const char* and that C string are compatible with that type, how come the compiler cannot call this function ? This is because the function is taking non-const reference to std::string objects. The constructor can't be used in this situation because the objects created would be temporaries, and you cannot get a non-const reference to a temporary object, as the called function may mutate it.
You can either create the std::string and pass them to the function:
std::string s1("String 1");
std::string s2("String 2");
std::string s3("String 3");
site(s1, s2, s3);
Or you can change the prototype of the site function to accept const reference. This is only possible if the function does not mutate the objects and you have access to the code:
// Declaration
void site(const std::string& s1, const std::string& s2, const std::string s3);
// Usage
site("String 1", "String 2", "String 3");