Re: cString operator= with same buffer

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sunday 20 November 2005 12:35, Holger Brunn wrote:
> Sascha Volkenandt wrote:
> > Why would you want this, or better why should two cStrings point to the
> > same buffer?
>
> Thanks for your reply, after putting together an example, I found that my
> problem is rather a symptom.
> Look at this code:
>
> #include "tools.h"
>
> cString str=cString("hello world");
>
> void func(cString string)
> {
>         str=string;
> }
>
> int main(int argc, char* argv[])
> {
>         printf("%s\n", *str);
>         func(str);
>         printf("%s\n", *str);
> }
>
> The problem is that str and string in func point to the same buffer. And
> even without assinging string to str, the second printf receives a freed
> buffer, for cString's destructor will be called for string when func
> returns.
>
> Then apart from dealing with the same-buffer thing, shouldn't cString have
> a copy constructor to take care of duplicating the buffer for this case? Or
> is cString intended to be passed by reference only?

You're absolutely right, I didn't think of such a scenario first, Apart from 
the fact that a call by const-reference would reduce overhead in this case, 
there are similar situations where that doesn't apply.

I've stumbled over one recently, but I solved it by surrounding it because I 
didn't think Klaus wanted to blow up the cString class any further. But now 
that Klaus almost accepted it already, I think it's a very good idea to 
implement a copy ctor :-).

Greetings,
Sascha


[Index of Archives]     [Linux Media]     [Asterisk]     [DCCP]     [Netdev]     [Xorg]     [Util Linux NG]     [Xfree86]     [Big List of Linux Books]     [Fedora Users]     [Fedora Women]     [ALSA Devel]     [Linux USB]

  Powered by Linux