Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of the & operator in C++ function signatures

I'm currently reading through Accelerated C++ and I realized I don't really understand how & works in function signatures.

int* ptr=# 

means that ptr now holds the address to num, but what does that mean?

void DoSomething(string& str) 

from what I understand that is a pass by reference of a variable (which means passing the address) but when I do

void DoSomething(string& str) {   string copy=str; } 

what it creates is a copy of str. What I thought it would do is raise an error since I'm trying to assign a pointer to a variable.

What is happening here? And what is the meaning of using * and & in function calls?

like image 867
Ziv Avatar asked Jul 29 '11 17:07

Ziv


People also ask

What is the rule for using the?

“The” is typically used in accompaniment with any noun with a specific meaning, or a noun referring to a single thing. The important distinction is between countable and non-countable nouns: if the noun is something that can't be counted or something singular, then use “the”, if it can be counted, then us “a” or “an”.

Why do you use the?

The is the definite article. The definite article is used with singular and plural nouns. It is used both with countable nouns and uncountable nouns: to make definite or specific reference to a person or a thing that has already been referred to.


2 Answers

A reference is not a pointer, they're different although they serve similar purpose. You can think of a reference as an alias to another variable, i.e. the second variable having the same address. It doesn't contain address itself, it just references the same portion of memory as the variable it's initialized from.

So

string s = "Hello, wordl"; string* p = &s; // Here you get an address of s string& r = s; // Here, r is a reference to s      s = "Hello, world"; // corrected assert( s == *p ); // this should be familiar to you, dereferencing a pointer assert( s == r ); // this will always be true, they are twins, or the same thing rather  string copy1 = *p; // this is to make a copy using a pointer string copy = r; // this is what you saw, hope now you understand it better. 
like image 101
unkulunkulu Avatar answered Oct 01 '22 03:10

unkulunkulu


The & character in C++ is dual purpose. It can mean (at least)

  1. Take the address of a value
  2. Declare a reference to a type

The use you're referring to in the function signature is an instance of #2. The parameter string& str is a reference to a string instance. This is not just limited to function signatures, it can occur in method bodies as well.

void Example() {   string s1 = "example";   string& s2 = s1;  // s2 is now a reference to s1 } 

I would recommend checking out the C++ FAQ entry on references as it's a good introduction to them.

  • https://isocpp.org/wiki/faq/references
like image 38
JaredPar Avatar answered Oct 01 '22 04:10

JaredPar