Is it bad to depend on index 0 of an empty std::string?

前端 未结 2 578
醉话见心
醉话见心 2020-12-30 18:30
std::string my_string = \"\";
char test = my_string[0];

I\'ve noticed that this doesn\'t crash, and every time I\'ve tested it, test is 0.

相关标签:
2条回答
  • 2020-12-30 19:04

    @Bartek Banachewicz's answer explains which circumstances allow you to make your assumption. I would like to add that

    this is bad programming.

    Why? For several reasons:

    1. You have to be a language lawyer just to be sure this isn't a bug. I wouldn't know the answer if not for this page, and frankly - I don't think you should really bother to know either.
    2. People without the intuition of a string being a null-terminated sequence of characters will have no idea what you're trying to do until they read the standard or ask their friends.
    3. Breaks the principle of least surprise in a bad way.
    4. Goes against the principle of "writing what you mean", i.e. having the code express problem-domain concepts.
    5. Sort-of-a use of a magic number (it's arguable whether 0 actually constitutes a magic number in this case).

    Shall I continue? ... I'm almost certain you have an alternative superior in almost every respect. I'll even venture a guess that you've done something else that's "bad" to manipulate yourself into wanting to do this.

    Always remember: Other people, who will not be consulting you, will sooner-or-later need to maintain this code. Think of them, not just of yourself, who can figure it out. Plus, in a decade from now, who's to say you're going to remember your own trick? You might be that confounded maintainer...

    0 讨论(0)
  • 2020-12-30 19:10

    C++14

    No; you can depend on it.

    In 21.4.5.2 (or [string.access]) we can find:

    Returns: *(begin() + pos) if pos < size(). Otherwise, returns a reference to an object of type charT with value charT(), where modifying the object leads to undefined behavior.

    In other words, when pos == size() (which is true when both are 0), the operator will return a reference to a default-constructed character type which you are forbidden to modify.

    It is not special-cased for the empty (or 0-sized) strings and works the same for every length.


    C++03

    And most certainly C++98 as well.

    It depends.

    Here's 21.3.4.1 from the official ISO/IEC 14882:

    Returns: If pos < size(), returns data()[pos]. Otherwise, if pos == size(), the const version returns charT(). Otherwise, the behavior is undefined.

    0 讨论(0)
提交回复
热议问题