自定义C ++字符串类

我正在创建一个类似于字符串类的类。我处于起步阶段,正在做一些实验。

假设添加了所有头文件

class String
{
      public: 
          int len; 
          char *str = NULL;                                                                       

      // Default constructor 
      String()
      {                                             
           len = 0;
           str = new char[1];             
           str[0] = '\0';
           printf("New memory: %p\n", str);
      }

    // Copy constructor
    String(const char *ch)
    {
        len = strlen(ch);  

        if (str != NULL)
        {
            printf("Old memory: %p\n", str);
            delete str; 
            printf("Deleted...\n");               
        }

        str = new char[len + 1];
        printf("New memory: %p\n", str);

        for (int i = 0; i <= len; i++)
            str[i] = ch[i];
    }
};


int main()
{
    String msg;

    std::cout << msg.len << std::endl;
    std::cout << msg.str << std::endl;

    msg = "Hello";
    std::cout << msg.len << std::endl;
    std::cout << msg.str << std::endl;
}

When I create a String object 1 byte of memory is allocated to store string and initialises with \0 on line String msg;

When copy constructor is called on line msg = "Hello"; it first checks for any previous allocation of memory and to avoid memory wastage it will delete that and recreates a new memory block.

The issue is when copy constructor is called line if (str != NULL) is not getting executed. It should execute because str is allocated a byte of memory earlier in default constructor and it is not NULL.

我可能错过了什么?

评论