Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
I have a definition like this in my class
public:
__declspec(property(get = getName, put = putName)) wstring Name;
wstring getName()	        {return m_sName;}
void putName(wstring Value)	{m_sName = Value;}

private:
wstring	m_sName;		


but when I do this, it would not get the correct pointer
TCHAR* tcharStr = const_cast<TCHAR*>(m_vecMFC[nMfcIndex]->Name.c_str());


Suppose these is a string like in the memory of m_sName:
41 00 72 00 32 00 20 00 32 00 32 00 00 00
but when I read memory of tcharStr, it becomes:
00 00 72 00 32 00 20 00 32 00 32 00 00 00

So, it becomes a NULL string.

But Why? Can anybody give me some idea??

Thanks!
Posted
Updated 28-Apr-11 21:15pm
v2

1 solution

It's not a good idea to store the pointers you get from c_str() calls. It is a much better idea to make a copy of the string using _tcscpy.

As to why it fails - because the method is declared like this:
wstring getName()


What you get when you call it is a copy of m_sName - which than disappears pretty quickly. And that's why the pointer you get from c_str() is no longer valid and strange things may happen (it may even work in release for a while and than fail out of the blue). If you want the actual m_sName you would need to define the function like this:
wstring& getName()


You can even have both functions in your code and than compare the pointers c_str() returns - see the difference?


But as I said at the start of this post - it is NOT a good idea to use the c_str() returned pointer. Always, always make a copy for a safer and better working programs :)

Best of luck!!
 
Share this answer
 
Comments
Olivier Levrey 29-Apr-11 3:58am    
Have my 5. Understanding how copy-constructors and references work is the key here.
Niklas L 29-Apr-11 4:29am    
Or better yet:
const wstring& getName() const {...}
Albert Holguin 29-Apr-11 10:19am    
my 5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900