Llamageddon
Llamageddon

Reputation: 3526

How should I handle string arguments in c++?

Say I want to write a function like this:

int get_some_int(string index) {
    ...perform magic...
    return result;
}

However, I also want to be able to call it like this:

int var = obj.get_some_int("blah");

However, I can't do this as const char[4] is not const string&

I could do:

int get_some_int(char* index) {
    ...perform magic...
    return result;
}

But this spews out a lot of warnings, implying it's not how it should be done.

What is the correct way to handle string arguments then?

Upvotes: 0

Views: 2567

Answers (3)

Loki Astari
Loki Astari

Reputation: 264749

It should work as you have done

int get_some_int(string index) {  // This works as std::string has a constructor
                                  // That takes care of the conversion
                                  // from `char const*`  which you char[4] 
                                  //decays into when passed to a function

But a better solution would be to use a const reference:

int get_some_int(string const& index) {  // works for the same reasson

Using the const here is an indication of the how function is supposed to work and conveys information about how the input is just being used. Also when used with methods that return a a const reference to a string (say from a const object) it will still work as expected.

Upvotes: 1

Tony
Tony

Reputation: 1626

Do a:

int var = obj.get_some_int(string("blah"));

if you feel more comfortable with it.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258698

I can't do this as const char[4] is not const string&

No, but std::string has a non-explicit conversion constructor so a temporary std::string is created, so you're in the clear. - http://ideone.com/xlg4k

Upvotes: 5

Related Questions