【发布时间】:2020-10-02 04:09:09
【问题描述】:
简介
我正在定义我自己的 String 类。除了我打算用来连接Strings 的+= 的定义之外,一切都很好
//expected behaviour
String c = "foo";
String d = "lala";
c+=d;
cout<<c;
应该输出:
foolala
我遇到了一个问题,因为它似乎确实可以正常工作,除了最后一位似乎没有传递指针。
这是代码(我省略了大部分其他定义,因为我认为它们对此没有用处)
代码
class String{
private:
unsigned int SizeS;
char *Buffer;
public:
String():SizeS(0){}
String(unsigned int i):SizeS(i){Buffer=new char[SizeS];}
String(const char *string)
{
//defines the initialiser
SizeS = strlen(string); //find out the length of the string
Buffer = new char[SizeS]; //allocate space for the entire string+1 for terminator
memcpy(Buffer,string,SizeS); //copy to buffer the whole thing
Buffer[SizeS]=0; //terminate the buffer with an end character
}
char * GetBuffer() const { return this->Buffer; }
String (const String& copied) :SizeS(copied.SizeS)
{
// defines how copying works
Buffer = new char[SizeS];
memcpy(Buffer,copied.Buffer,SizeS);
}
// this is where the issue is ------------------
String* operator += (const String& to_concat)
{
unsigned int newSize = this->SizeS + to_concat.SizeS;
String *p = new String(newSize) ;
memcpy(p->Buffer,this->Buffer,this->SizeS);
memcpy(p->Buffer+this->SizeS,to_concat.Buffer,to_concat.SizeS);
std::cout<<p->Buffer<<std::endl;
return p;
}
// this is where the issue ends ------------------
};
std::ostream& operator<< (std::ostream& stream, const String& other) { stream << other.GetBuffer(); return stream; }
int main()
{
String c="foo";
std::cout<<c<<std::endl;
c += c;
std::cout<<c<<std::endl;
}
预期输出
foo
foofoo
foofoo
实际输出
foo
foofoo
foo
问题
我做错了什么?据我了解,我用指针p 覆盖了指针c,但似乎c 没有改变。这是为什么呢?
解决方案
在阅读了 cmets 和建议后,我想出了这个可行的解决方案。
String& operator += (const String& to_concat)
{
unsigned int newSize = this->SizeS + to_concat.SizeS;
char* p = new char[newSize];
memcpy(p,this->Buffer,this->SizeS);
memcpy(p+this->SizeS,to_concat.Buffer,to_concat.SizeS);
delete[](this->Buffer);
this->Buffer=p;
this->SizeS=newSize;
return *this;
}
【问题讨论】:
-
请包含所有相关代码,例如缺少的构造函数。问题应包含minimal reproducible example
-
你应该将结果连接到 *this->Buffer
-
您需要检查所有内存分配和零 (nul) 终止符的写入 - 它们无法始终如一地工作。您的构造函数将
Buffer分配为SizeS+1字符并通过写入Buffer[SizeS+1]来完成。这会导致未定义的行为。您的operator+=()有相反的问题 - 它没有分配足够的字符来存储 nul 字符,但也没有将 nul 字符写入缓冲区。您的operator<<()和operator+=()中的输出语句都假定存在nul 终止符,如果不存在则具有未定义的行为... -
不要让我知道
operator+=()返回一个指向动态分配的String的指针。这是等待发生的内存泄漏。 -
@Peter 它不是在等待;内存泄漏就在程序中。
标签: c++ class pointers operator-overloading