Does containers get copied when used as parameters?

G

Gaijinco

When I do something like:

void Foo(string s)
{
// something here
}

does ti copy S, or as with a char* it only copies the location where
the string is?

More generally when I use a container as parameter does it pays to pass
a reference as a parameter to avoid the container being copies?

Thanks!
 
E

Eric Jensen

When I do something like:
void Foo(string s)
{
// something here
}

does ti copy S, or as with a char* it only copies the location where
the string is?

It copies s.
More generally when I use a container as parameter does it pays to pass
a reference as a parameter to avoid the container being copies?

Yes.

void Foo(string& s)
{
// something here
}

//eric
 
E

Eric Jensen

More generally when I use a container as parameter does it pays to pass

I forgot to say: that is if you're not going to change the value of the
parameter. However, in some cases where you change the value of the
parameter and the caller no longer will use the variable it still pays. But
i recommend that you will only pass a variable as a reference if you're not
changing it.

void foo (const std::string& s) {
// whatever
}

//eric
 
H

Howard

Eric Jensen said:
I forgot to say: that is if you're not going to change the value of the
parameter. However, in some cases where you change the value of the
parameter and the caller no longer will use the variable it still pays.
But i recommend that you will only pass a variable as a reference if
you're not changing it.

void foo (const std::string& s) {
// whatever
}

Are you only referring to a const reference here? Passing by non-const
reference is a perfectly fine way to pass objects whose contents may be
modified.

-Howard
 
E

Eric Jensen

Are you only referring to a const reference here? Passing by non-const
reference is a perfectly fine way to pass objects whose contents may be
modified.

I nearly meant, if the argument are not to be changed, always pass as a
reference.
And if the caller expect that the argument is not to be manipulated, then do
not pass as a reference if the function modifies the object. And of course
you can still pass the argument as a reference, if the purpose of your
function is to modify the object for the caller.

//eric
 

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

No members online now.

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,227
Latest member
Daniella65

Latest Threads

Top