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 below

Obj.set_val("10h;");

      

I am getting the following error:

error: no matching function for call to 'Node::set_val(const char [5])'

      

I assumed the string in "" is the same as string

in C ++, why am I getting this error? What needs to be changed below?

+3


source to share


3 answers


You accept std::string

by non-const link. Non-trailing references cannot bind to rvalues, for example "10h;"

, so you cannot pass literals into this function.

If you are not going to change the argument, you must take your argument by reference-to-const:

void Node::set_val(const string &val)
//                 ^^^^^

      

Thus, the temporary std::string

will be created from yours const char[5]

and transferred to set_val

.



You can improve this by taking value string

by value and move

into it vector

:

void Node::set_val(string val)
{
    this->val.push_back(std::move(val));
}

      

This will prevent unnecessary copies from being created.

+8


source


So, in C ++, const char * is implicitly convertible to std :: string, because std :: string has an (implicit) constructor that takes const char *. So the compiler is trying here to create a temporary std :: string object to call your function, like this:

Node.set_val(std::string("10h;"));

      

However, since you have specified the set_val parameter as a non-const reference to a std :: string, the compiler cannot perform this conversion operation due to the fact that temporary objects cannot be bound to non-const Recommendations.

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

      

Everything will compile (the latter requires C ++ 11 or higher), but seeing your use case, I would recommend using the second or third. To explain why, try reading a little about move semantics in C ++ 11.

The important point to remove here is that const char * is implicitly converted to std :: string by creating a temporary object, and temporary objects cannot be passed to functions that accept non-const references.

+2


source


You pass "10h;"

which is a const char array.

Fix it by passing in the string: Obj.set_val(string("10h"));

and edit the function to take the string by value:

void Node::set_val(string val) { /* */ }

      

Or maybe better, edit your function to take const string&

:

void Node::set_val(const string &val) { /* */ }

      

0


source







All Articles