Reference/value semantics in constructors.

S

Squeamizh

This is something that has been bothering me for a while.

Assume the following two class definitions:

class Inner {
int a;
int b;
...
};

class Outer {
Inner a;
int aa;
int bb;
};

Further assume that Outer's constructor takes an Inner object as an
argument. Keeping in mind that Outer contains its own Inner object
and not a reference to a 'foreign' Inner, should Outer's constructor
be:

Outer(Inner a) : a(a) {...}

OR

Outer(Inner& a) : a(a) {...}

?

I know they both have the same outcome, but I'm asking this question
from a performnce standpoint. Assume Inner is larger than four bytes.

Thanks.
 
M

Mike Wahler

Squeamizh said:
This is something that has been bothering me for a while.

Assume the following two class definitions:

class Inner {
int a;
int b;
...
};

class Outer {
Inner a;
int aa;
int bb;
};

Further assume that Outer's constructor takes an Inner object as an
argument. Keeping in mind that Outer contains its own Inner object
and not a reference to a 'foreign' Inner, should Outer's constructor
be:

Outer(Inner a) : a(a) {...}

OR

Outer(Inner& a) : a(a) {...}

?

I know they both have the same outcome, but I'm asking this question
from a performnce standpoint. Assume Inner is larger than four bytes.

If the type of the argument will be 'large', passing by reference is
usually preferred. If the argument must/will not be modified, pass
by const reference.

The actual 'physical' speed and sizes of data types will depend upon
your implementation and platform, so the only way to find out for
sure which is 'faster' would be to test them.

-Mike
 
S

Sergei Matusevich

Outer(Inner a) : a(a) {...}

OR

Outer(Inner& a) : a(a) {...}

In your particular case, I would suggest

Outer(const Inner& new_a) : a(new_a) {...}

Passing parameters by value usually make sense only when copying is
inexpensive (e.g. for int), or when you have some specific logic in the
object's copy constructor (e.g. std::auto_ptr, boost::shared_ptr)

Hope this helps!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top