Path: utzoo!attcan!uunet!mcsun!inria!litp!geocub!anthes From: anthes@geocub.greco-prog.fr (Franklin Anthes) Newsgroups: comp.lang.c++ Subject: Getting a string class to work. Message-ID: <1760@geocub.greco-prog.fr> Date: 20 Mar 90 13:31:01 GMT References: <1759@geocub.greco-prog.fr> Reply-To: anthes@geocub.greco-prog.fr (Franklin Anthes) Organization: Greco-Programmation, Bordeaux, France. Lines: 60 I'm just starting out with C++. I want to build a very basic String class. BTW I wonder why such basic classes as String, etc. standard in C++? It is a good idea of course to do something like this once or twice during the learning process, but reinventing each wheel can become tedious after a while. Anyway, here's a small piece of my code : typedef unsigned long StringLenType; class String { char *buf; StringLenType len; public: String(); String(const char *); String(const String &); ~String(); String& operator=(const String&); friend String& operator+(String&,String&); } String& String::operator=(const String& s) { len = s.len; delete buf; buf = new char[len+1]; strcpy(buf,s.buf); return *this; } String& operator+(String& s1,String& s2) { String*& ret = new String( s1.len + s2.len ); memcpy(ret->buf,s1.buf,s1.len); memcpy(ret->buf+s1.len,s2.buf,s2.len+1); return *ret; } I want to implement operations like : String s1; String s2("foo"); String s3("bar"); s1 = s2 + s3; // s1 == "foobar" Now the code above "works", but the space allocated by operator+ is not deleted. Is there an elegant way to do this sort of thing in C++? A possible solution (kludge) would be to add a tag into the String class, to indicate whether the string is a temporary which should be deleted after the result is calculated. Hmm garbage collection can come in handy sometimes. A big merci, for those willing to help me me out. -- Frank Anthes-Harper : Bien le bonjour de la France anthes@geocub.greco-prog.fr