Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

C++ design pattern

Name: Anonymous 2009-07-22 8:55

Can you help me? I'm wondering what is the best pattern for the situation I'll describe.

SITUATION 1


class Inside {
  public:
    Inside(int a, int b) {
        yada = a;
        foo = b;
    }
    int yada;
    int foo;
};

class Container {
  private:
    Inside *c;
  public:
    Container(Inside *i) {
        c = i;
    }
    ~Container() {
        delete c;
    }
};


This situation allows you to avoid deleting the parameter passed as argument, so you can do:

Container c(new Inside(10, 20));

and the Inside instance will be deleted automatically. Drawbacks following:

Inside i(10, 20);
Container c(&i);

FUCK, i've deleted the stack!

SITUATION 2


class Inside {
    ...
};

class Container {
  private:
    Inside *c;
  public:
    Container(Inside *i) {
        c = i;
    }
    ~Container() {}
};


Now you can do:

Container c(new Inside(10, 20));

but you get memory leaks, so you need to take around with you a pointer to the Inside instance, and this is pretty unconfortable!

How would you do?

Name: Anonymous 2009-07-22 11:37

Don't listen to >>16. Use std::auto_ptr and you don't have to worry about manually freeing memory.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List