C++动态分配,是我使用新的正确方法
C++ Dynamic Allocation, Is my use of new correct?
我在动态分配方面遇到了问题。在我的代码中我是否正确初始化了动态数组?。当我尝试为类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
的+=
足够大以容纳结果
我把它当作练习。
使用标准名称重新实现标准库函数是非常令人困惑的。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 在c++中使用动态分配的问题
- 使用递归模板动态分配的多维数组
- 对具有动态分配的内存和析构函数的类对象的引用
- 删除类成员的动态分配内存的最佳方法是什么
- C++类内部结构动态分配的方法
- 动态分配一维结构数组:两种方法
- 保留动态分配的数组而不为删除而烦恼的最佳方法
- 在c++中的赋值运算符重载方法中删除旧的动态分配内存
- 在类方法中使用新运算符动态分配内存的寿命和范围是多少
- 如果从动态分配的对象调用方法,是否可以以某种方式内联(编译器优化)
- 在C++中动态分配向量的安全方法是什么
- 释放方法 C/C++ 中动态分配的 char*
- 如何在方法中返回数组的动态分配结构
- 在C++中的类的方法中传输动态分配的矩阵
- C++动态分配,是我使用新的正确方法
- 释放类的实例是否也会释放由其对象/方法动态分配的内存?
- 有没有任何方法可以在C++中获得动态分配的数组的长度
- 防止类动态分配的任何方法