Re: Is this String class properly implemented?
On 18 Apr., 17:22, kevintse.on...@gmail.com wrote:
Oh, I have clicked the wrong link, and only replied to the author SG
Let me include it here.
On Sat, Apr 18, 2009 at 5:18 PM, kevintse.on...@gmail.com wrote:
On Apr 18, 8:44 pm, SG <s.gesem...@gmail.com> wrote:
kevintse.on...@gmail.com wrote:
[...]
[...]
Actually, I intended to write an *unmutable* String, which only had
logical length, its length was not supposed to be changeable. This is
also the Java implementation of the String class. huh, I took the idea
from Java.
OK.
operator const wchar_t* () const {
return value;
}
This is dangerous since this allows *implicit* conversion to a pointer
that points to memory that is *managed* by the string object. If the
string object dies and deletes the char array you basically have an
invalid pointer.
So if I want to return a C style string, I have to allocate new memory
for the string? and let the caller of the function deal with the
deallocation of the memory? But, most of the time, that I call this
function is just to obtain a C style string that can be output with
"iostream" related functions.
I haven't said anything against returning your internal wchar_t*
converted to pointer-to-const. I reasoned against an implicit
conversion operator.
~String(){
size = 0;
delete [] value;
}
"size = 0;" is pretty much useless here.
Set size to zero is necessary, because I return "size" directly when
the "length()" function is called, this function tells the actual size
of the String. And this is definitely more efficient than calling
"wcslen(value)" everytime we need a "size".
You're not entirely familiar with the concept of destructors, are you?
String trim();
String trimLeft();
String trimRight();
...are just three examples that could have been free functions
instead. Also, since you seem to be creating a new String object for
the result as return value you seem to have forgotten 'const'
qualifiers.
I was refering to the Java implementation of the class in which these
functions return new Strings, so, you know, I copied... oh, Java does
not have a pointer, or a reference...
I know that. But that's beside the point.
OK, these functions are all supposed to return references for better
efficiency, cause I am using C++.
....and what kind of reference would that be? A reference to the
object itself? Do you want these functions to mutate the String
object or just return a modified copy?
Never ever return a reference to a non-static function-local object.
Never ever.
String operator=(String& str);
Your copy assignment doesn't take a reference-to-const String?
Oh, I have forgotten that...
Cheers!
SG