c++ - Adding Multiple string values -


i have function gets 3 input(mostly lpcstr) , combines them , return value:

template<typename t> inline t  const& lpcombine(t const& lpstr1, t const& lpstr2, t const& lpstr3) {     std::string str1, str2, str3, combined;     lpcstr lpcombiend = "";      str1 = lpstr1;     str2 = lpstr2;     str3 = lpstr3;      combined = str1 + str2 + str3;      lpcombiend = combined.c_str();      return lpcombiend; } 

if print value of lpcombined in same function it's correct , strings or numbers concatenated if print returned value lpcombine function function main function printed value weird , unreadable:

╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠

what problem?

when t == lpcstr, i.e. const char*, function returns const reference raw char pointer.

the main problem pointer points memory of std::string object (combined) defined inside function body:

std::string ..., combined; ...  lpcombiend = combined.c_str();  return lpcombiend; 

(note seem have typo, lpcombiend should lpcombined.)

when function terminates, combined std::string object destroyed, lpcombiend pointer points garbage.

in particular, using visual c++ in debug builds, uninitialized memory marked 0xcc byte sequences. note 0xcc ascii code 204 = (box drawing character double line vertical , right), have in output.

so, should consider returning std::string object instead.

i'd question declaration , design of template function. make sense have const t& input string parameters? if t e.g. pcwstr (const wchar_t*), str1 = lpstr1; assignment inside function body won't work, str1 std::string, , can't create std::string const wchar_t* raw pointer.


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -