Stl string return by const reference vs. const char *
Someone who returns a string reference is better suited for two options. If the string is modified internally, the previously returned string reference will be valid, but const char *
probably not.
Better than either of these choices might be to simply return by value.
std::string getData3() const { return data_; }
Also, I would suggest not prefixed variables with underscore and get rid of that operator using namespace std;
.
a source to share
Both are a little dangerous because your object might go out of scope or its memory might get freed. But you will still have a pointer or reference to one of its members.
If you really want to do this, it only depends on whether you want to access the string methods or not. There c_str()
const char*
may also be a memory to be freed from you.
If _data
not that big, maybe just return string
instead const string&
.
a source to share
I usually prefer getData2()
. const char*
returned by a method c_str()
can only be used as long as data
non-const methods are not called. After that, the content const char*
is undefined. By returning const char*
, you hide this problem. If the user of the class needs to use a C style string, he can call c_str()
himself on the returned one const string&
.
Here we also assume that the user getData2()
reasonably assumes that the returned reference will only be available to him as long as the class object A
is not destroyed.
a source to share
Refunds are const string&
better. If you need one const char*
, you can simply call getData2().c_str()
, which is almost identical to what it does getData1()
.
Remember std::string
better than strings const char*
because they preserve length, not null terminated. This means that if you want to get the length of that string, it strlen(getData1())
is an O (n) getData2().length()
operation , but it is an O (1) operation.
a source to share