code_junkie

create std::string from char* in a safe way

Nov 12th, 2011
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.66 KB | None | 0 0
  1. string foo()
  2. {
  3. char *p = get_string();
  4.  
  5. string str( p );
  6. free( p );
  7. return str;
  8. }
  9.  
  10. string
  11. foo()
  12. {
  13. shared_ptr<char> p(get_string(), &free);
  14. string str(p.get());
  15. return str;
  16. }
  17.  
  18. string foo()
  19. {
  20. const char* p = get_string();
  21. const Cleanup cleanup(p);
  22. const std::string str(p != NULL ? p : "");
  23.  
  24. return str;
  25. }
  26.  
  27. struct Cleanup {
  28. void* toFree;
  29. Cleanup(void* toFree) : toFree(toFree) {}
  30. ~Cleanup() { free(toFree); }
  31. private:
  32. Cleanup(Cleanup&);
  33. void operator=(Cleanup&);
  34. };
  35.  
  36. string foo()
  37. {
  38. char *p = get_string();
  39. ScopeGuard sg = MakeGuard(&free, p);
  40. string str( p );
  41. return str;
  42. }
Add Comment
Please, Sign In to add comment