C++ const string literals and custom string class -


in c++ string literals "hello" const , immutable. wanted make custom string class strings not const chars, can changeable

here snippet of code might illustrate i'm trying do:

#include <iostream>  class string {   public:      char * p_start;      string(char * strsourc) // constructor       {         p_start = strsourc;       } };  int main()  {   string mystring("hello");   // create object mystring, send "hello" string literal argument    std::cout << mystring.p_start << std::endl;  // prints "hello"    *mystring.p_start = 'y';  // attempt change value @ first byte of mystring.p_start    std::cout << mystring.p_start << std::endl;  // prints "hello" (no change)    mystring.p_start = "yellow";  // assigning string literal p_start pointer     std::cout << mystring.p_start << std::endl;  // prints yellow, change works.  thought mystring "hello" const chars, immutable    return 0; } 

so, i'm confused. i've looked everywhere , says string literals, "hello", immutable, each of char bytes unchangeable. though managed assign yellow p_start pointer, changing first letter. though changing single letter h y through dereferencing h pointer didn't anything.

any insights me, thanks.

i think you're confusing pointer , pointee.

p_start = "yellow", you're changing value of pointer, point "yellow". *p_start = 'y', you're changing value of pointee, content p_start points to, not itself. said, "yellow" const chars, behaviour try modify them ub.

you can make copy of in ctor, can modify chars, managed class. yes, new copy, won't waste of memory. , have no choice if want them changable.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -