开发者

std::string vs string literal for functions

开发者 https://www.devze.com 2023-01-05 23:26 出处:网络
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?

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 t开发者_JAVA技巧his 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?


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.


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).


I think it would be enough to pass an reference rather than value of string. I mean:

bool Message::hasTag(const string& tag)

That would copy only the reference to the original string value. Which must be created somwhere anyway, but outside of the function. This function would not copy its parameter whatsoever.

Since m_tags is a vector of strings anyway (I suppose), const string& parameter would be better idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消