Click to See Complete Forum and Search --> : to return a CString
Serge Iwa
September 7th, 1999, 08:38 AM
i defined a public class member which returns CString. (myStr = parse->getvalue("some");)
Is it good style, or its better to return an pointer to it?
Wayne Fuller
September 7th, 1999, 09:00 AM
It is a lot faster to return a pointer or a reference to it. The problem is, though, if you do this it cannot be a local member. Because when it goes out of scope there is junk in memory. But if the string is part of your class, then use a pointer of a reference.
For example:
class CSomeClass
{
private:
CString m_str;
public:
const CString& GetString() { return m_str; }
};
This would be the way to do a member string.
But if it is not a persistant member, then the other way is fine, but there will be a little bit of performance problem because of the copying of classes.
Maybe a better way would be to pass the CString as a parameter in the function if the string is not a member of the class.
September 9th, 1999, 06:25 AM
There is only one problem:
GetString() returns the ptr to a private member - you can now change the private data of the class !!!
Return only a CString takes more time (creates a copy behind your back) but it protects the private data.
Try it out.
chris
Wayne Fuller
September 9th, 1999, 07:26 AM
You are right it does return a reference to it. But if you define it as returning a "const" value, you are not allowed to change it.
ChristianH
September 14th, 1999, 04:13 AM
Oops... you are right!
Thanks Chris
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.