C++动态分配,是我使用新的正确方法

C++ Dynamic Allocation, Is my use of new correct?

本文关键字:方法 动态分配 C++      更新时间:2023-10-16

我在动态分配方面遇到了问题。在我的代码中我是否正确初始化了动态数组?。当我尝试为类String编写+运算符成员时,它不会返回我想要的内容。任何关于正确道路的指导都是很好的。

Ex。

String s1("One");
String s2("Two");
String s3 = s1+ s1;
cout <<s3;
//Output is OneTwo
cout <<s1;
//OUtput is OneTwo.

我也不明白为什么我不能在构造函数中添加delete[]buf。

class String{
public:
String (const char *s =""):buf(new char[strlen(s)]){
    buf = strdup(s);    
       };
String (const String &s):buf(new char[strlen(s.buf)]){
    buf = strdup(s.buf);
    delete []buf;
};
String operator =(const String &s){
    return buf =strdup(s.buf);
};
char & operator [] (int index){
    assert(inBounds(index));
    return buf[index];
};
int size()
{
    return strlen(buf);
};
String operator  + (const String s){
    delete []buf;
    char *temp = new char[strlen(buf)+strlen(s.buf)];
   ///NEed to ask about t*his acan get this operator tor work
    cout<< s.buf;
            return temp;
    };
String operator += (const String s){
    strcpy(buf + strlen(buf),s.buf);
    return buf;
};
void print(ostream & out){
    out << buf;
};
void read (istream & in){
    in >> buf;
};
~String(){
    //delete [] buf;
};
private:
    bool inBounds(int x){
    return x >= 0 && x < strlen(buf);
};
static int strlen(const char *s){
    int len =0;
    for(int i=0;s[i] != '';i++)
        len++;
    return len;
};
static char *strcpy(char *dest,const char *src){
    int i=0;
    for(;(dest[i] = src[i]); ++i);
    dest[i] = '';
    return dest;
};
static char *strdup(const char *s){
    char * buf;
    buf = new char[strlen(s)+1];
    int i=0;
    for(;s[i] != '';i++)
        buf[i] = s[i];
    buf[i] = '';
    return buf;
}  
char * buf;
};

您的第一个构造函数

String (const char *s ="") : buf(new char[strlen(s)]){
    buf = strdup(s);
}

首先分配一个太小一个字符的缓冲区,然后通过将buf指向strdup的结果(内存泄漏)将其丢弃。

你想要

String (const char *s ="") : buf(new char[strlen(s) + 1]){
    strcpy(buf, s);
}

String (const char *s ="") : buf(strdup(s))
{
}

您的第二个构造函数

String (const String &s) : buf(new char[strlen(s.buf)]){
    buf = strdup(s.buf);
    delete []buf;
};

具有与内存泄漏相同的问题,并且增加了立即解除分配buf的复杂性。

你想要类似的东西

String (const String& s) : buf(strdup(s.buf))
{
}

+解除分配buf,分配一个未初始化(且太小)的缓冲区,打印buf(未定义),然后返回由未初始化缓冲区生成的String

加法运算符不应修改*this;它应该使用+=并且看起来像

String operator+ (const String& s) const 
{
    String result = *this;
    result += s;
    return result;
};

这使得需要重新分配buf+=足够大以容纳结果
我把它当作练习。

使用标准名称重新实现标准库函数是非常令人困惑的。