Search code examples
c++charconstantsc-strings

Create own string using const char * vs char *


I want to create my own string storage (class) and I know something about const char * and char *.

This is a part of my source:

class str_n
{
private:

    char * _str;

public:

    str_n(const char * str)
    {
          std::size_t Read_len = strlen(str);
          _str = (char *) malloc(Read_len + 1);
          memcpy(_str, str, Read_len + 1);
    }
};

I used char * and const char * for my _str and I know if I use const char * I need to copy it to char * whlie I want to use some other functions inside of my class and also using const char * is faster (very faster (about 2x)) than char * to save the const char * param content.

Now my question: If you want to create new string storage, you use const char * or char *?


Solution

  • Use char *, if your str_n is mutable. You're wrong on the part that const content is modifiable. For example, this:

    const char *foo = "foo";
    foo[0] = 'a';
    

    won't compile. Trying to circumvent it with const_cast is not a viable option:

    const_cast<char *>(foo)[0] = 'a';
    

    as it is undefined behavior, and usually crashes, as foo is put in read-only memory.

    So, if your string is mutable, you must copy the contents of str (the parameter for the constructor) in your example (you don't have the option of using const char * as storage, and omitting the copy to make your program faster -- I suppose you meant "2x faster" because you omitted the copy).

    A note: you should use new instead of malloc, it is more c++-ish (you won't need to cast to char * the result of new char[...])