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?
Printable View
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?
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.
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
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.
Oops... you are right!
Thanks Chris