& -Operator / C ++, Explanation

I would be very grateful if someone could explain to me how I can recognize / understand when to use the and operator.

As noted:

& Addresses

and

The address of a variable can be obtained by specifying the variable name with an ampersand (&) character, known as an address operator. For Example:

foo = & myvar;

This will assign the address to the variable myvar foo; preceded by the variable name myvar with the address-operator (&), we no longer assign the contents of the variable foo itself, but its address.

But everything is too abstract for me.

For example: When we generate integers in the main function why

if (!myDoc.setContent(&file, errorMsg, errorLine)) {

false?

// Code lines here →

QString errorMsg;
    int errorLine;
   QString errorMsg;
int errorLine;
if (!myDoc.setContent(&file, &errorMsg, &errorLine)) {


        ...
    }

      

and how, for example, you can find out here that

QString maxString(const QString& s, int len)

but not

QString maxString(const QString s, int len)

      

// Here's a second example.

QString maxString(const QString& s, int len) {
        if (s.size() < len) return s;
        else return s.left(len)+"...";
    }



    void showTree(QTextStream& out, const QDomNode& node, const int intent) {
        QString text;
        if (node.nodeType() == QDomNode::ElementNode) {
            ...
            }

        } else if (node.nodeType() == QDomNode::TextNode) {
            text = node.nodeValue().trimmed();
            if (text.isEmpty()) return; // keine Ausgabe leerer Textknoten
            text = "#text: "+maxString(text, 20);
        }
       ...

    }

      

+3


source to share


2 answers


&

used in a variable declaration is different from when it is used in code (I mean the part that gets executed).

When running the code, it can be understood as "address". So,

int i = 7;
std::cout << i; // output: 7
std::cout << &i; // output: 0x7fff2af8900 (or any other, mostly random, hex number)

      

The output of the number &i

is the address where the variable is stored. Variable addresses can be used in many ways (mainly in what is called pointer arithmetic). For example, by language definition, an array in memory is stored sequentially and continuously. Thus, it int i[4];

defines an array 4

int

s, which is stored as cells next to each other in memory. You can use i[1]

to touch the second element of this array, and i

(without []

) contains the address for the first member.
Thus, i == &i[0]

it is always true for arrays.

However, in the ad , this is called a link.



int value = 7;
int& ref = value; // with this, you can look at value using ref variable
value = 8;
std::cout << ref; // output: 8

      

EDIT:
When a function is called with arguments, all of its arguments are copied and your function works with its own data. If the function has a view bool check_validity(LargeData data)

that somehow processes tons LargeData

and then returns true

if the data is valid and false

otherwise. You are effectively copying a whole bunch of data into this function. And when, after returning from this function, the copy is lost. Now copying (time) is expensive, and if you don't need that copy why are you copying it. If you pass this package LargeData

using a link (as LargaData&

or better const LargeData&

to disable unwanted modification) the only thing that actually copies is some constant pointer (most likely8Bytes

) instead of whole data (which can be 10 MB or 500 GB or even more).

So as far as your code QString maxString(const QString& s, int len)

is s

concerned, only exists because you don't want to waste time copying varibale's input if you only want to read its contents.

Now myDoc.setContent(&file, &errorMsg, &errorLine)

- this is probably some function that (using some rules) fills in file

and returns true

if it was successful and false otherwise, and if it was false it also fills in errorMsg

and errorLine

with some information as to why it failed. But how do we define this function so that we can have many output variables. Easy, we will pass the address of the variable to this function and write to this address.

+2


source


These are two different uses of the operator &

:

first use , in if (!myDoc.setContent(&file, errorMsg, errorLine))

, operator &

returns the address of the file object. In this case, it is necessary and so, because the function setContent()

was probably declared like this:

setContent(FileType * inputFile, ..., ...);

      

When you declare a function, using an operator *

means you will receive the address as a parameter. In this case inputFile

, a memory address is expecting, and by saying &file

you are passing a memory address file

as a parameter.

the second use of the operator &

is in the function declaration. By using the and operator in a function declaration, you expect the object to be passed by reference. If you don't already know this, you should look at the difference between passing parameters by value or by reference.

In a few words, passing a parameter by value means that you will pass a copy of the object, so the passed object will not be modified after the function call. Passing a value by reference means that the function can modify the passed object.

Example:



void maxString(QString& s, int len) // s passed by reference
{
    s = QString::ToUpper(s, len); // Just made that up
}
QString myString = "My string";
maxString(myString, myString.length());

// myString is now "MY STRING"

      


void maxString(QString s, int len) // s passed by value
{
    s = QString::ToUpper(s, len); // Just made that up
}
QString myString = "My string";
maxString(myString, myString.length());

// myString is still "My string"

      

There are other differences in C ++ between pass by value or reference.

Basically, passing by value means that you will create a copy of the passed object by effectively calling the copy constructor on that object. This is undesirable in most cases as it uses up CPU time for no reason. To overcome this, is used const ClassName &

. This means that you will be passing a constant reference to the object (i.e. no time wasted in the copy constructor) and the function will not be able to modify the object.

You should be looking for differences between passing by value / reference and using a constant.

+1


source







All Articles