0

Here's the code

class C {
public:
    void baz() {std::cout<<"~";}
};

class B {
public:
    B() {c = new C();}
    ~B() {delete c;}
    void bar() {c->baz();}

private:
    C* c;
};

class A {
public:
    A(): b(B()) {};
    A(B arg_b): b(arg_b) {};
    void foo() {b.bar();};
private:
    B b;
};


int main() {
    A a;
    a.foo();

    A aa{B()};  // will give the exit code 134 error
    aa.foo();
}

As shown in the code, Class A has two constructors, calling the second constructor as above will give the following message Process finished with exit code 134 (interrupted by signal 6: SIGABRT), while the first works fine.

Could someone please explain what is the difference between this two methods? what is the correct way of passing an instance as the initial value of a class member?

EDIT

As has πάνταῥεῖ has commented, delete is applied twice for the same pointer c. Adding the copy constructor B(const B& arg_b) : c(new C(*arg_b.c)) {} to B solves the problem, assuming the copy-constructor of C is valid.

dontloo
  • 10,067
  • 4
  • 29
  • 50
  • 1
    I'd guess the implicitly generated copy constructor of `B` is used, and the `delete` is applied twice for the same pointer. Try to create your own copy constructor (and assignment operator), that handles the `B::c` member correctly. – πάντα ῥεῖ Mar 02 '17 at 10:33
  • @πάνταῥεῖ Ah, thanks that makes much sense, however actually I don't have total control over the source code of Class B, is there anyway to do that without modifying the code of Class B? – dontloo Mar 02 '17 at 10:37
  • "I don't have total control over the source code of Class B". It's broken. You either cause it to be fixed somehow, or don't use it. – n. m. could be an AI Mar 02 '17 at 10:43
  • @dontloo _"is there anyway to do that without modifying the code of Class B? "_ Yes, take it in `A` by reference. – πάντα ῥεῖ Mar 02 '17 at 10:44
  • 1
    If `A` is under your control, you could wrap all uses of `B` (e.g. `class Bsafe { B b; /* .... */ };` and you `delete` the copy-constructor of `Bsafe` so you cannot accidentally copy it ... other than that you dont have much option than understanding the rules of the language (which is complicated) and manually trying to avoid making copies. – M.M Mar 02 '17 at 11:50
  • @πάνταῥεῖ thanks a lot! – dontloo Mar 02 '17 at 13:55
  • @M.M thanks a lot! – dontloo Mar 02 '17 at 13:55

0 Answers0