c++ when to return a const char* instead of a std:string

  • A+
Category:Languages

In the class below is there any benefit or reason why speak() returns a const char* instead of a std::string?

class Animal { protected:     std::string m_name;      Animal(std::string name)     : m_name(name)     {     }  public:     std::string getName() { return m_name; }     const char* speak() { return "???"; } }; 


What a string literal such as "???" does is it tells the compiler to include a piece of global memory containing that particular sequence of characters (plus the character '/0' at the end). The string literal expression has a value of type const char* pointing to that piece of global memory.

What that means is that in this very particular circumstance, it's safe to pass around the pointer. Note that the following function

std::string speak() { return "???"; } 

has the same function body but a rather different code path. The string literal expression (the global memory, the pointer) is still there, but it is used as an argument to the constructor for std::string; it is implicitly converted to std::string.

That constructor for std::string dynamically allocates some memory (well not in this case with the short string optimization, probably) and copies from the pointer you give it.

So in this very particular case, where you have a string literal and nothing else, you can return a const char*. It will probably get implicitly converted to std::string when passed to another function which expects it, so const char* isn't all that much of an optimization.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: