Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string vs string literal for functions

I was wondering, I normally use std::string for my code, but when you are passing a string in a parameter for a simply comparison, is it better to just use a literal?

Consider this function:

bool Message::hasTag(string tag)
{
    for(Uint tagIndex = 0; tagIndex < m_tags.size();tagIndex++)
    {
        if(m_tags[tagIndex] == tag)
            return 0;
    }

    return 1;
}

Despite the fact that the property it is making a comparison with is a vector, and whatever uses this function will probably pass strings to it, would it still be better to use a const char* to avoid creating a new string that will be used like a string literal anyway?

like image 379
Tomas Avatar asked Mar 06 '26 19:03

Tomas


2 Answers

If you want to use classes, the best approach here is a const reference:

bool Message::hasTag(const string& tag);

That way, redudant copying can be minimized and it's made clear that the method doesn't intend to modify the argument. I think a clever compiler can emit pretty good code for the case when this is called with a string literal.

Passing a character pointer requires you to use strcmp() to compare, since if you start comparing pointers directly using ==, there will be ... trouble.

like image 181
unwind Avatar answered Mar 08 '26 07:03

unwind


Short answer: it depends.

Long answer: std::string is highly useful because it provides a lot of utility functions for strings (searching for substrings, extracting substrings, concatenating strings etc.). It also manages the memory for you, so the ownership of the string cannot be confused.

In your case, you don't need either. You just need to know whether any of the objects in m_tags matches the given string. So for your case, writing the function using a const char *s is perfectly sufficient.

However, as a foot note: you almost always want to prefer std::string over (const) char * when talking about return values. That's because C strings have no ownership semantics at all, so a function returning a const char * needs to be documented very carefully, explaining who owns the pointed to memory (caller or callee) and, in case the callee gets it, how to free it (delete[], delete, free, something else).

like image 44
Frerich Raabe Avatar answered Mar 08 '26 07:03

Frerich Raabe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!