c++ - Pointers vs references and cleaning it all up -


consider code:

#include <iostream> using namespace std;  struct some_other_base {     // members };  struct foo : some_other_base {     int value;     static foo *createptr(int param)      {          foo *res = new foo();          res->value = param;          return res;     }     static foo &createref(int param)     {         return *createptr(param);     } };  int main() {     foo *ptr = foo::createptr(2);     foo &ref = foo::createref(4);     foo local = foo::createref(5);      cout << "ptr: " << ptr->value << endl;     cout << "ref: " << ref.value << endl;     cout << "local: " << local.value << endl;      delete ptr;     delete &ref;     return 0; 

requirements:

  1. foo::createptr method may return null under circumstances (allocation failed , handled, invalid parameters, etc.)
  2. foo pod, not aggregate

what want: few possible delete calls (and memory leaks).

my observations:

  1. i can use foo::createptr, check null , delete afterwards
  2. i can use foo::createref, can't check null , still have delete
    1. i make foo::createref return special instance when createptr null. null checking, still not deleting.
  3. i use local variant, think have memory leak right there (the createptr(5) never gets deleted, copied local)
    1. this highly ineffective because there's unnecessary alloc , copy
    2. i can't use brace initialization because foo not aggregate

is there way declare local variable of foo type , initialize within declaration such automatically deleted on function exit?

if object can't created, throw exception. it's more useful anyway, gives more context why object couldn't created , allows program fix problem. avoid problems delete because don't use new. if type used polymorphically, need use smart pointers std::unique_ptr or std::shared_ptr.

#include <iostream> #include <stdexcept> using namespace std;  struct some_other_base {     // members };  struct creationfailure : std::runtime_error {     creationfailure(const std::string& s) :         std::runtime_error(s)     {      } };  struct foo : some_other_base {     int value;      foo(int value) :          some_other_base(), // pass constructor arguments         value(value)     {         // additional actions         if(/* creation failed */)             throw creationfailure("out of memory");     } };  int main() {     foo local(2);      cout << local.value << endl;     return 0; } 

if can't add constructors, same logic can moved factory function:

foo createfoo(int v) {     foo f;     f.value = v;     if(/* creation failed */)         throw creationfailure("out of memory");     return f; } 

Comments

Popular posts from this blog

tcpdump - How to check if server received packet (acknowledged) -