1. 程式人生 > 其它 >【C++】 string變數不能使用memset

【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