Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

I find a BIG bug of VS 2005 about string class!

2 views
Skip to first unread message

Lighter

unread,
Sep 4, 2006, 4:08:51 AM9/4/06
to
I find a BIG bug of VS 2005 about string class!

#include <iostream>
#include <string>

using namespace std;

string GetStr()
{
return string("Hello");
}

int main(int argc, char *argv[])
{
const char* p = GetStr().c_str();

cout << p << endl;

cin.get();
}

============================

Run the code above, Dev C++ will normally output the string "Hello",
however, VS 2005 should output an empty string!

In my opinion, string class is vital to almost every C++ program, and
VS 2005 as a C++ compiler is widely used by programmers, if string
class is wrongly implemented by Microsoft, that will be a disaster!

Lighter

unread,
Sep 4, 2006, 4:25:36 AM9/4/06
to
I'm the OP. VS 2005 did right. I am wrong.

Because GetStr() returns a temporary object, so the object will be
deleted after the function returns.

I'm very sorry for my misunderstanding.

Joseph M. Newcomer

unread,
Sep 4, 2006, 11:35:40 AM9/4/06
to
I am surprised this works at all. The fact that it ever worked is a miracle. You are
extracting a pointer to the underlying representation of an object that is about to be
deleted (I document the same error in my essay on CStrings). What you should have done
was
string p = GetStr();
which would then store the object, and << should properly work with type string.

I don't know how well STL works with Unicode, but this code won't port to Unicode.

Note that for MFC programming, CString is a much better choice than string.
joe

Joseph M. Newcomer [MVP]
email: newc...@flounder.com
Web: http://www.flounder.com
MVP Tips: http://www.flounder.com/mvp_tips.htm

David Wilkinson

unread,
Sep 4, 2006, 12:04:52 PM9/4/06
to
Joseph M. Newcomer wrote:
> I am surprised this works at all. The fact that it ever worked is a miracle. You are
> extracting a pointer to the underlying representation of an object that is about to be
> deleted (I document the same error in my essay on CStrings). What you should have done
> was
> string p = GetStr();
> which would then store the object, and << should properly work with type string.
>
> I don't know how well STL works with Unicode, but this code won't port to Unicode.
>
> Note that for MFC programming, CString is a much better choice than string.
> joe
>

Joe:

If you do

typedef std::basic_string<TCHAR> tstring;

then STL handles Unicode just fine. And it doesn't have dangerous
conversion constructors like CString.

David Wilkinson

Joseph M. Newcomer

unread,
Sep 4, 2006, 10:43:13 PM9/4/06
to
Thank you. That's a good piece of information to know.
joe

Tom Serface

unread,
Sep 5, 2006, 1:32:41 PM9/5/06
to
Great tip David!

Tom

"David Wilkinson" <no-r...@effisols.com> wrote in message
news:%23XvWbvD...@TK2MSFTNGP06.phx.gbl...

0 new messages