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 13:28

Who owns the Inside object? If a Container instance owns the Inside object, then make a copy of it when you assign it and delete it in the deconstructor. If it's not owned by the Container instance, then don't delete it.

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