std::string nightmare

Started by
4 comments, last by GameDev.net 18 years, 8 months ago
Hello, everyone! There's a small misunderstanding with stl strings. The problem, it seems, plagued our whole project, and I have no idea what is wrong here. Let's say there's an object with string as one of its members, something like this: struct testObj { std::string text; }; now, in case we do something like this: testObj a, b; a.text = "12345678901234567890"; b = a; OMG, The assignment actually works! "b.text" has the value "12345678901234567890"? now, how come that be true at all? This: "b = a;" is a bitwisecopy, right? Well, anyway, in this case it could be assumed, that our strings a.text and b.text internally point to the same mem location and changing one of them will affect the other one. Let's test it -- a.text = ""; nah, bad assumption, b.text = "12345678901234567890". Ok, the question here is: "How does std::string know of the assignment operation "b = a;" ?" I'm all lost here... There's something that I have no solution for, the following code gives me mem leak of 32 bytes in vs7.1: struct testObj { std::string text; }; void InitStr( testObj &a ) { testObj b; b.text = "12345678901234567890"; // //b.text = "123456789012345"; -- works fine, I guess //is't due to some internal (16 bytes?) string //buffer, that is used for short strings. short //string optimization, I guess // a = b; } int main() { testObj test; InitStr( test ); return 0; } I've got no idea how to solve this little puzzle...
away from comlex ideas i live like rembo -- day by day
Advertisement
the default assignment operator actually invokes the assignment operator for all contained types, but if you haven't defined one for your class you'll simply get a bitwise copy of all primitive members and all all userdefined types will have theri respective op= called.
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
the std::string class is a typedef, typedef basic_string<char> string;
and the basic_string class implements a = operator. no magic there...just some operator overloading, which is a part of C++.

but i have no idea about the mem leak ....sorry
what are you using to detect memory leaks? that surly doesn't leak for me.
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
Quote:Original post by DigitalDelusion
what are you using to detect memory leaks? that surly doesn't leak for me.


#define _crtdbg_map_alloc
#include
#include

...

_CrtDumpMemoryLeaks();
Original post by Anonymous Poster
Quote:Original post by DigitalDelusion
what are you using to detect memory leaks? that surly doesn't leak for me.


thanks to all the question is closed :)
memleaks becouse the destructor execs after _CrtDumpMemoryLeaks()

This topic is closed to new replies.

Advertisement