It is impossible to avoid a temporary instance of std::string that copies character data. Please note that this cost is very low and does not require dynamic memory allocation if your standard library implementation uses short string optimizations.
However, if you often need to proxy C-style strings, you can come up with custom solutions that will bypass this distribution. It can pay off if you need to do this very often, and your lines are long enough to not use short line optimizations.
If you need only a very small subset of string functions (for example, only assignment and copies), then you can write a small special string class that stores the const char * pointer and a function to free memory.
class cheap_string { public: typedef void(*Free)(const char*); private: const char * myData; std::size_t mySize; Free myFree; public:
Then you can use this class as:
std::map<cheap_string, int> m1; auto i = m1.find(cheap_string::proxy("foo"));
A temporary instance of cheap_string does not create a copy of the character buffer, such as std::string , but retains the stored copy semantics for storing cheap_string instances in standard containers.
notes : if your implementation does not use return value optimization, you need to find an alternative syntax for the proxy method, for example, a constructor with special overload (using a special proxy_t type Γ la std::nothrow to post a new one).
source share