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 10:56

If you're writing a toy program, use Python. Or just leak memory or do whatever is convenient.
For anything else, always place allocation and deallocation together in the same section of the code. Always. Always.

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