Can we pass a char* to const string&? - c++

Is the following code acceptable in C++? If so, what happens? Does it create a temp string variable and pass its address?
void f(const string& s) {
}
const char kJunk[] = "junk";
f(kJunk);

Yes, it's acceptable. The compiler will call the string(const char *) constructor and create a temporary that will be bound to s for the duration of the call. When the fall to f returns the temporary will be destroyed.

The argument that is the character array is implicitly converted to a temporary object of type std::string and the compiler passes const reference to this temporary object to the function. When the statement with the call of the function will finish its work the temporary object will be deleted.

Does it create a temp string variable and pass its address?
Yes, it's equivalent to:
void f(const std::string& s) {
}
const char kJunk[] = "junk";
f(std::string(kJunk));

Related

Correct way to use reference lvalues

My code is the following:
void parentheses (int n, string& str, int left, int right){
... irrelevant...
}
void solve(int n){
parentheses(n,"",0,0);
}
However, this will give me an error, telling me that cannot bind non-const lvalue reference of type std::__cxx11::string& ... to an rvalue of type ‘std::__cxx11::string. In this case, if I still want to pass the string in as a reference, how should I modify my functions? I don't want to make them const because I want to functions to modify the original string, and I want them to be & precisely because I want to edit their values.
The function parentheses expects an lvalue in the std::string parameter, i.e. a named variable. However, you have supplied an rvalue (temporary) in this call:
parentheses(n,"",0,0);
An empty string object is created and passed to parentheses. You can avoid this problem by changing the definition of parentheses like so:
void parentheses (int n, const string& str, int left, int right)
Here str will bind to an rvalue/temporary, but you won't be able to change its value in the function. However, if you want to change the value of str you have to define a string variable and pass that to the function.
Example:
void solve(int n){
std::string str;
parentheses(n,str,0,0);
}
Note: no need to assign str to "" as a string is empty by default.
the function needs a memory to change, you didn't specify which.
declare a string to hold what you want to pass and where to get the output to.
string s = "";
and pass it to the function
I'm not really sure what the purpose is of passing "" by reference is, as any value put there will get lost.
Anyway, to answer your question, create a variable and pass it instead:
void solve(int n){
std::string tmp = "";
parentheses(n,tmp,0,0);
}
If you don't care about the value stored in tmp, you can just ignore it. But you need some type of variable there, even if you don't care about what gets eventually put there by the routine.
Your parentheses() function takes a non-const reference to a std::string object, so it expects an actual std::string object on the other side of the reference - an lvalue (something that can be assigned to).
But your solve() function is not passing a std::string object, it is passing a string literal instead. So the compiler creates a temporary std::string object - an rvalue - which then fails to bind to the reference, because a temporary object can't be bound to a non-const reference, only to a const reference. That is what the error message is telling you:
cannot bind non-const lvalue reference of type std::__cxx11::string& ... to an rvalue of type ‘std::__cxx11::string
solve() needs to explicitly create an actual std::string object to pass to parentheses():
void solve(int n){
std::string s = "";
parentheses(n,s,0,0);
}
If you want to change the values of your string for any string that is passed as a paramenter (lvalue, as well rvalue), just initialize a variable with the intended content and pass it to your function.
But if you want to treat lvalue strings diferently from rvalue strings, just overload your original function. i.e.:
void parentheses (int n, string& str, int left, int right){
... irrelevant... // change strings values as desired
}
void parentheses (int n, string&& str, int left, int right){
... irrelevant... // string as rvalue
}

Understanding assignment of const reference to non-cost data member

I am reviewing C++ references any am trying to reason why the following piece of code complies:
#include <string>
class Foo {
public:
Foo(const std::string& label)
: d_label(label) {}
private:
std::string d_label;
};
int main(int argc, const char** argv) {
Foo("test");
return 0;
}
Here, we are assigning a reference to a const string to a string. In doing so, is a copy of label made that is non-const? If so, why is it that we can make a copy of a const object that is itself non-const? Otherwise, what exactly is going on here, in terms of copy constructor/assignment calls?
In C++ the keyword const actually means read-only. To make a copy of an object, you don't need write access. Therefore, you can copy a const std::string into an std::string.
Also note, that copying in C++ means making a deep copy by default. This is called value semantics. Hence, manipulating the copied string will not do anything to the original string.
Now to your last question: What is going on in the following line?
Foo("test");
The type of "test" is const char[5]. The compiler searches for a matching constructor of Foo. Since "test" is implicitly convertible to std::string via the
basic_string<CharT,Alloc>::basic_string( const CharT * s, const Alloc & a = Alloc() );
constructor, this conversion will be performed, i. e. a temporary std::string is constructed from "test". A const reference to this temporary is then passed to the constructor
Foo::Foo( const std::string & label );
This constructor in turn calls std::strings copy constructor in order to construct the d_label member of Foo:
basic_string<CharT,Alloc>::basic_string( const basic_string & other );
C++ offers both reference semantics and value semantics: Objects have values, and then you can take references to objects.
std::string d_label
d_label is an object holding a string value. It is considered to own the bytes holding the string as a memory resource. This notion of ownership rationalizes using d_label as an interface to modify the string.
const std::string& label
label is a read-only reference to a string. This is not quite the same as "a reference to a const string." It refers to an object that may be (and probably is) not const.
: d_label(label)
This initializes d_label with the content of label using a copy constructor. You may then do what you like with the copy. You know that the process of copying won't modify the underlying object of label because label was declared const &.
Here no assignments take place. d_label(label) initializes the variable d_label with label which subsequently ends up calling copy constructor of string type.
Let's have a closer look:
Foo("test"); initializes const std::string& label with "test" which its type is const char[5]
Here a string reference (label) is getting initialized with a value having type const char[5]. This initialization is valid since "test" through decaying to const char * can be passed to one of string constructors which gets a const char *.
Now label is a reference to a real string object storing "test".
Then, d_label(label) initializes Foo::d_label with the object referred to by label.
At this point copy constructor of string type is called and constructs the Foo::d_label.

STL Push_back string in vector

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) { /* */ }

how does std::string manages this trick?

i just wrote a function:
void doSomeStuffWithTheString(const std::string& value) {
...
std::string v = value;
std::cout << value.c_str();
...
}
but then i call this with
doSomeStuffWithTheString("foo");
and it works. So i would have thought that this to work (a const char* to initialise a implicit instance of std::string) the value would have to be passed by value, but in this case is passed by (const) reference.
Is by any chance a implicit temporal std::string instantiated from const char* when the reference is const? if not, then how this possibly work?
EDIT
what happens if the function is overloaded with
void doSomeStuffWithTheString(const char* value);
which one will choose the compiler?
The std::string type has an implicit conversion (via constructor) from const char*. This is what allows the string literal "foo" to convert to std::string. This results in a temporary value. In C++ it's legal to have a const & to a temporary value and hence this all holds together.
It's possible to replicate this trick using your own custom types in C++.
class Example {
public:
Example(const char* pValue) {}
};
void Method(const Example& e) {
...
}
Method("foo");
Yes, a temporary std::string is constructed from the string literal.
Exactly, using std::string default constructor
"the value would have to be passed by value, but in this case is passed by (const) reference."
There is a C++ feature where it is possible to pass a temporary value (in this case, a temporary std::string implicitly converted from the const char *) to an argument of const-reference (in this case, const std::string &) type.

What's the difference between these two local variables?

const std::string s1("foo");
const std::string& s2("foo");
Not sure how they are different but I'm seeing evidence of both usages. Any ideas?
const std::string s1("foo");
This declares a named std::string object as a local variable.
const std::string& s1("foo");
This declares a const reference to a std::string object. An unnamed, temporary std::string object is created with the contents "foo" and the reference is bound to that temporary object. The temporary object will exist until the reference goes out of scope.
In this particular case, there is no observable difference between the two: in both cases you end up with a std::string that can be accessed via the name s1 and which will be destroyed when s1 goes out of scope.
However, in some cases, there is a difference. Consider, for example, a function that returns by reference:
const std::string& get_reference_to_string();
If you initialize s1 with the result of calling this function, there is a difference between:
const std::string s1(get_reference_to_string());
const std::string& s1(get_reference_to_string());
In the first case, a copy of the referenced string is made and used to initialize s1. In the second case, s1 is simply bound to the std::string to which the returned reference refers: no copy is made.
They are identical in meaning, due to the way constant references can bind to temporaries plus string having an implicit conversion from char*.
For clarity and readability, prefer the non-reference.
The first instance creates a constant string variable initialized to hold "foo". The second one creates a constant reference to a string and then initializes that constant reference to point at a temporary string that was initialized to hold "foo".
const std::string s1("foo"); creates a std::string object on the stack and initializes it with the const char* string "foo." const std::string& s1("foo"), on the other hand, is a const reference to an implicitly constructed std::string.