0

I have a class class1 with its a constructor class1(int i) and a copy constructor class1(const class1& other).

Instances of class1 are created dynamically, since the int argument is not known at compile time.

My problem is that I have to pass this pointer between a producer object and a consumer object:

void producer::produceAndSend(...) {
    class1 *c1 = generate(...); 
    consumerObj.set(c1);
}

class consumer {
    class1 *internalC;
    void set(class1 *c);
}

void consumer::set(class1 *c) {
    this->internalC = c; //This only copies the pointer, not the content
}

I would like to store a copy of the object pointed by c1 and this copy must be pointed by internalC. How can I achieve this?

the_candyman
  • 1,563
  • 4
  • 22
  • 36

1 Answers1

6

Instances of class1 are created dynamically, since the int argument is not known at compile time.

That's not what dynamic allocation is for. You can create an object with automatic storage duration with runtime parameters. In fact, by not using dynamic allocation, your problem is solved automatically and won't involve you leaking memory.

void producer::produceAndSend(...) {
    class1 c1 = generate(...); 
    consumerObj.set(c1);
}

class consumer {
    class1 internalC;
    void set(class1 c);
}

void consumer::set(class1 c) {
    this->internalC = c; //This only copies the pointer, not the content
}
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • as I said, the constructor of `class1` is `class1(int i)`. What you wrote cannot work. – the_candyman Jun 22 '14 at 17:10
  • @the_candyman, Yes, it can. Easily. Please read the relevant section of your book again. – chris Jun 22 '14 at 17:10
  • 1
    @the_candyman For what reason? Because `consumer` will default construct `internalC`? Well you have some options. The first is to give `class1` a default constructor, the second is to give `consumer` a constructor which constructs `internalC` by passing it some `int`, and the third option is to use `boost::optional internalC;` if you want it to be that `internalC` doesn't exist until it's set. – Joseph Mansfield Jun 22 '14 at 17:12
  • I don't have a default constructor. I only have the constructor with input arguments – the_candyman Jun 22 '14 at 17:13
  • ["give consumer a constructor which constructs internalC by passing it some int"](http://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor) – chris Jun 22 '14 at 17:14
  • Consumer is created independently from the parameter `int i` used to construct the object. `i` is evaluated at runtime, it can change and the creation of `internalC` can be perfomed a lot of time. Anyway, I think I got your point, but I prefer a way without altering the class or using boost – the_candyman Jun 22 '14 at 17:16