【C++】 string变量不能使用memset

使用memset会造成两个问题:

  1. 内存泄漏;

  2. =赋值时出现crash

string类内部是使用char* data维护,使用new分配空间,直接memset会导致string内部data=NULL, 造成内存泄露;

如果这时使用string s1 = s2; 会出现NULL= new char(size),导致crash。

如:

#pragma once
#include<iostream>
#include<assert.h>
#include<string.h>
using namespace std;
namespace TY
{
  class String
  {
  public:
    typedef char* iterator;
    iterator begin()
    {
      return _str;
    }
    iterator end()
    {
      return _str + _size;
    }
    //构造函数
    String(const char* str = "")
    {
      if (nullptr == str)
      {
        assert(false);
        return;
      }
      _size = strlen(str);
      _capacity = _size;
      _str = new char[_capacity + 1];//加1保存'\0'
      strcpy(_str, str);
    }
    //拷贝构造
    String(const String& s)
      :_str(new char[s._capacity +1])
      , _size(s._size)
      , _capacity(s._capacity)
    {
      strcpy(_str, s._str);
    }
    //赋值操作
    String& operator=(const String& s)
    {
      if (this != &s)
      {
        String tmp(s._str);
        swap(_str, tmp._str);
      }
      return *this;
    }
    //析构函数
    ~String()
    {
      if (_str)
      {
        delete[] _str;
        _str = nullptr;
        _size = 0;
        _capacity = 0;
      }
    }
    char* c_str()
    {
      return _str;
    }
    private:
    char* _str;
    size_t _size;
    size_t _capacity;
    }
    void TestString1()
  {
    String s1("hello");
    String s2("world");
    String copy(s1);
    cout << s1.c_str() << endl;
    cout << s2.c_str() << endl;
    cout << copy.c_str() << endl;
    //利用迭代器打印String中 的元素
    String::iterator it = s1.begin();
    while (it != s1.end())
    {
      cout << *it << " ";
      ++it;
    }
    cout << endl;
    //范围for
    for (auto e : s1)
    {
      cout << e << " ";
    }
    cout << endl;
  }
    
};

 

参考链接

https://blog.csdn.net/tangya3158613488/article/details/86599693

https://www.cnblogs.com/beixiaobei/p/10914267.html

 

 

posted @ 2021-10-26 19:54  我自逍遥笑  阅读(94)  评论(0编辑  收藏  举报