views:

58

answers:

2

If the constructor for Door looks like this:

Door::Door(Doorknob doorknob) : m_doorknob(doorknob) { }

Then you would instantiate a Door like this:

Doorknob doorknob;
Door door(doorknob);  // Does an object copy of doorknob occur here?

It seems like if you store Doorknob as a pointer, you can explicitly avoid the copy:

Door::Door(Doorknob * doorknob_ptr) : m_doorknob_ptr(doorknob_ptr) { }

Instantiate Door like this:

Door door(new Doorknob);

But now you have to make sure to delete doorknob inside Door's destructor, which seems ugly.

What is the preferred approach?

+5  A: 

Better approach is to pass with const reference:

Door::Door(const Doorknob& doorknob) : m_doorknob(doorknob) { }

Otherwise a copy of Doorknob will be passed to constructor and used as parameter for m_doorknob constructor.

pingw33n
moala
Ates Goral
+2  A: 

More important than minimizing the number of copy constructor calls is that your code correctly models the problem space.

Door owns the doorknob; i.e. the lifecycle of DoorKnob is the same as that of Door. Thus, Door should manage the lifecycle of Doorknob.

The second solution is not be preferred for that reason. You are relying on the client to manufacture the Doorknob object, which you then store a pointer to, which is a violation of RAII.

Your first solution is acceptable, but as you note, as the problem of making an unnecessary copy of the Doorknob object, since copies as a parameter.

The ideal solution is to have contructor take in a reference, as @pingw33n's solution does. Or, since it may not make sense to construct a Doorknob outside of a door, have your Door constructor create the Door.

JohnMcG
My concern with passing in Doorknob as a reference is that potentially Doorknob can go out of scope before Door does. (For example, if Door was declared on the heap and Doorknob was declared on the stack -- this would be a bad thing.) Perhaps the answer is simple "don't do that" -- but at this point, I am already "new"-ing the Door...so it seems like I need to "new" the Doorknob as well.
Runcible
I was imagining your constructor would then make a copy of the Doorknob passed into it -- than the only copy is the one you need.
JohnMcG