开发者

When is the right time to use *, & or const in C++?

开发者 https://www.devze.com 2023-01-20 06:27 出处:网络
I was studying pointers references and came across different ways to feed in parameters. Can someone explain what each one actually means?

I was studying pointers references and came across different ways to feed in parameters. Can someone explain what each one actually means?

I think the first one is simple, it's that x is a copy of the parameter fed in so another variable is created on the stack. As for the others I'm clueless.

void doSomething1(int x){
    //code
}
void doSomething2(int *x){
    //code
}

void doSomething3(int &x){
    //code
}
void doSomething3(int const &x){
    //code
}

I also see stuff like this when variables are declared. I don't understand the differences between them. I know that the first one will put 100 into the variable y on the stack. It won't create a new address or anything.

//example 1
i开发者_如何学运维nt y = 100;

//example 2
int *y = 100;

//Example 3: epic confusion!
int *y = &z;

Question 1: How do I use these methods? When is it most appropriate?

Question 2: When do I declare variables in that way?

Examples would be great.

P.S. this is one the main reasons I didn't learn C++ as Java just has garbage collection. But now I have to get into C++.


//example 1
int y = 100;

//example 2
int *y = 100;

//Example 3: epic confusion!
int *y = &z;

I think the problem for most students is that in C++ both & and * have different meanings, depending on the context in which they are used.
If either of them appears after a type within an object declaration (T* or T&), they are type modifiers and change the type from plain T to a reference to a T (T&) or a pointer to a T (T*).
If they appear in front of an object (&obj or *obj), they are unary prefix operators invoked on the object. The prefix & returns the address of the object it is invoked for, * dereferences a pointer, iterator etc., yielding the value it references.

It doesn't help against confusion that the type modifiers apply to the object being declared, not the type. That is, T* a, b; defines a T* named a and a plain T named b, which is why many people prefer to write T *a, b; instead (note the placement of the type-modifying * adjacent the object being defined, instead of the type modified).

Also unhelpful is that the term "reference" is overloaded. For one thing it means a syntactic construct, as in T&. But there's also the broader meaning of a "reference" being something that refers to something else. In this sense, both a pointer T* and a reference (other meaning T&) are references, in that they reference some object. That comes into play when someone says that "a pointer references some object" or that a pointer is "dereferenced".

So in your specific cases, #1 defines a plain int, #2 defines a pointer to an int and initializes it with the address 100 (whatever lives there is probably best left untouched ), and #3 defines another pointer and initializes it with the address of an object z (necessarily an int, too).


A for how to pass objects to functions in C++, here is an old answer from me to that.


From Scott Myers - More Effective C++ -> 1

First, recognize that there is no such thing as a null reference. A reference must always refer to some object.Because a reference must refer to an object, C++ requires that references be initialized.

Pointers are subject to no such restriction. The fact that there is no such thing as a null reference implies that it can be more efficient to use references than to use pointers. That's because there's no need to test the validity of a reference before using it.

Another important difference between pointers and references is that pointers may be reassigned to refer to different objects. A reference, however, always refers to the object with which it is initialized

In general, you should use a pointer whenever you need to take into account the possibility that there's nothing to refer to (in which case you can set the pointer to null) or whenever you need to be able to refer to different things at different times (in which case you can change where the pointer points). You should use a reference whenever you know there will always be an object to refer to and you also know that once you're referring to that object, you'll never want to refer to anything else.

References, then, are the feature of choice when you know you have something to refer to, when you'll never want to refer to anything else, and when implementing operators whose syntactic requirements make the use of pointers undesirable. In all other cases, stick with pointers.


Read S.Lippmann's C++ Premier or any other good C++ book. As for passing the parameters, generally when copying is cheap we pass by value. For mandatory out parameters we use references, for optional out parameters - pointers, for input parameters where copying is costly, we pass by const references


Thats really complicated topic. Please read here: http://www.goingware.com/tips/parameters/. Also Scott Meiers "Effective C++" is a top book on such things.


void doSomething1(int x){ //code } This one pass the variable by value, whatever happens inside the function, the original variable doesn't change

void doSomething2(int *x){ //code } Here you pass a variable of type pointer to integer. So when accessing the number you should use *x for the value or x for the address

void doSomething3(int &x){ //code } Here is like the first one, but whatever happens inside the function, the original variable will be changed as well

int y = 100; normal integer

//example 2 int *y = 100; pointer to address 100

//Example 3: epic confusion! int *y = &z; pointer to the address of z


void doSomething1(int x){
//code
}
void doSomething2(int *x){
//code
}

void doSomething3(int &x){
//code
}

And i am really getting confused between them?

The first is using pass-by-value and the argument to the function will retain its original value after the call.

The later two are using pass-by-reference. Essentially they are two ways of achieving the same thing. The argument is not guarenteed to retain its original value after the call.

Most programmers prefer to pass large objects by const reference to improve the performance of their code and provide a constraint that the value will not change. This ensures the copy constructor is not called.

Your confusion might be due to the '&' operator having two meanings. The one you seem to be familiar with is the 'reference operator'. It is also used as the 'address operator'. In the example you give you are taking the address of z.

A good book to check out that covers all of this in detail is 'Accelerated C++' by Andrew Koening.


The best time to use those methods is when it's more efficient to pass around references as opposed to entire objects. Sometimes, some data structure operations are also faster using references (inserting into a linked list for example). The best way to understand pointers is to read about them and then write programs to use them (and compare them to their pass-by-value counterparts).

And for the record, knowledge of pointers makes you considerably more valuable in the workplace. (all too often, C++ programmers are the "mystics" of the office, with knowledge of how those magical boxes under the desks process code /semi-sarcasm)

0

精彩评论

暂无评论...
验证码 换一张
取 消