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-23 3:21

>>4
Horrible, horrible solution.

>>1
This is a definite problem, and you shouldn't leave the code this way no matter how you've documented it. There are a few solutions...

- As >>17 said, use std::auto_ptr or boost::shared_ptr. This is ugly, but will prevent you from screwing up memory management (unless you go out of your way to do something stupid). However, it forces you to allocate an object to pass into it. You are likely to want to stack-allocate an Inside object.

- A better solution in this case is to just copy it. Your Inside object only has two ints, so it should support the copy operation; the overhead of an allocation is far greater than the extra int. However, this won't allow you to dynamically update the Inside without refreshing the container. For your Inside class (which seems to be just a point), this should not be dynamic anyway; it's obviously something intrinsic to the Container which should be abstracted away.

If you *really* need the update to be dynamic, use boost::shared_ptr, or if that's not available, simply do not delete the object in Container; delete it by the class it was created in.

Here's fixed code:


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

class Container {
  private:
    Inside c;
  public:
    explicit Container(const Inside& i) {
        c = i;
    }
    ~Container() {}
};


And now you can do this:


Inside i(5, 3);
Container c(i);


Or simply:


Container c(Inside(5,3));

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