Many times I have come across code something like the below:
class AClass {
public:
std::string getName();
};
std::string AClass::getName() {
return "I am returning";
}
Here the member function converts the string constant to std::string while returning. This is in my opinion not necessary. This cast away some flexibility. I mean this way of converting to a std::string while returning to function does not make much sense.
Reason:
If we need in any place to get the name as const char* I need to reverse by calling string::c_str()
const char* pName = instanceOfClassA.getName().c_str();
However, keeping the return type as const char* has some benefits:
const char* AClass::getName() const {
return "I am returning";
}
1. const char* pName = instanceOfClassA.getName().getName(); // No Conversion will take place
2. std::string sName = instanceOfClassA.getName().getName(); // Conversion happens to std::string
So, only based on usage conversion happens. It delays conversion until needed.
Now arguably, we can say that why not use c_str() to get something as const char*. I mean, let the function remain as below:
std::string AClass::getName() {
return "I am returning";
}
The usage may be like this:
const char* pName = instanceOfClassA.getName().c_str();
/*Other use of pName.... */
c_str() will return [internal buffer (C++ 11) of std::string as] const char*. But it's not reliable.
Why? The explanation is given in the link
In a line, to simplify it, we can't use data pointed by c_str() past the lifetime of std::string object or changed by a function. In both of those cases, the pointer will be invalidated.
Comments