Do pointers to string literals remain valid after a function returns?

后端 未结 4 514
温柔的废话
温柔的废话 2020-11-30 09:48

Is the pointer returned by the following function valid?

const char * bool2str( bool flg )
{
    return flg ? \"Yes\" : \"No\";
}

It works

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 10:28

    Technically Yes it is valid.
    The strings have static storage durataion.

    But that is not the whole story.

    These are C-Strings. The convention in C-Libraries and funcctions is to return a dynamically allocated string that should be freed. ie A pointer returned is implicitly passing ownership back to tha caller (As usuall in C there are also exceptions).

    If you do not follow these conventions you will confuse a lot of experienced C-Developers that would expect this convention. If you do not follow this standard expectation then it should be well documented in the code.

    Also this is C++ (as per your tags). So it is more conventional to return a std::string. The reason for this is that the passing of ownership via pointers is only implied (and this lead to a lot of errors in C code were the above expectation was broken but documented, unfortunately the documentaiton was never read by the user of the code). By using a std::string you are passing an object and their is no longer any question of ownership (the result is passed back as a value and thus yours), but because it is an object there is no questions or issues with resource allocation.

    If you are worried about effeciency I think that is a false concern.

    If you want this for printing via streams there is already a standard convention to do that:

    std::cout << std::boolalpha << false << std::endl;
    std::cout << std::boolalpha << true  << std::endl;
    

提交回复
热议问题