【C++】 string變量不能使用memset
使用memset會造成兩個問題:
-
-
=賦值時出現(xiàn)crash
string類內(nèi)部是使用char* data維護(hù),使用new分配空間,直接memset會導(dǎo)致string內(nèi)部data=NULL, 造成內(nèi)存泄露;
如果這時使用string s1 = s2; 會出現(xiàn)NULL= new char(size),導(dǎo)致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;
}
//構(gòu)造函數(shù)
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);
}
//拷貝構(gòu)造
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;
}
//析構(gòu)函數(shù)
~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;
}
};
