This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Difference between pointer variable and reference variable in C++
I saw this simple code the other day, and I consider myself a beginner with pointers, although I have about a year and half experience with c++. Anyways...
Whats the difference between
int a = 0;
int &b = a;
and
int a = 0
int *p = &a;
Obviously, p holds the address of a, but b is a reference to a, meaning I can change the value of a with b. But I can also do the same thing with p. So what are advantages or disadvantages?
A reference must always be initialized
A reference can't be null
Once initialized, a reference can't be changed to be an alias of a different object.
I think it comes down to how you plan to use the variables afterwards in your program. Both statements appear to do the same thing (in this limited scope).
The first approach seems to be (in my opinion) poor programming practice since it may not be obvious later in the program that changing the value of b also changes the value of a. In the second, at least it is known that p is a pointer, so you should expect the side effects that come with changing the value to which it points.
Related
This question already has answers here:
Two different values at the same memory address
(7 answers)
Closed 5 years ago.
Consider the following code:
I declare a new reference end assign it to value a via const_cast. Then I just increase the reference value print the addresses and values.
#include <iostream>
using namespace std;
int main()
{
const int a = 7;
int &b = const_cast<int&>(a);
++b;
cout<<"Addresses "<<&a<<" "<<&b<<endl;
cout<<"Values "<<a<<" "<<b<<endl;
}
//output
Addresses 0x7fff11f8e30c 0x7fff11f8e30c
Values 7 8
How can i have 2 different values in the same address??
Because modifying a variable declared to be const is undefined behavior, literally anything can happen.
Modifying a constant object gives undefined behaviour, so your program could (in principle) do anything.
One reason for leaving this behaviour undefined is to allow the optimisation of replacing a constant variable with its value (since you've stated that the value can never change). That's what is happening here: a is replaced with the value 7 at compile time, and so will keep that value whatever you try to do to it at run time.
Even though const_cast may remove constness from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const invokes undefined behavior.
check out the example here for more illustration:
http://en.cppreference.com/w/cpp/language/const_cast
Any attempt to modify an object that is itself declared const by means of const_cast results in undefined behavior according to the ISO C++ Standard.
When the we refer "const object", it intends to say that the memory where the object is located may be write-protected. That is, a variable or expression of const type may denote an object stored in write-protected memory and any attempt to modify the object results in undefined behavior
EDIT: Refer this site for more info
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1994/N0571.asc
This question already has answers here:
What are the differences between a pointer variable and a reference variable?
(44 answers)
Closed 7 years ago.
I have a kinda deep C experience but I am a C++ beginner. References seem to be easier to use than pointers, but it drives me crazy. I think all references can be replaced with pointers. In my case, pointers are not that hard because I spent tons of times studying them. Is it common among C++ programmers to use references or is it just recommended??
One thing that references prevent is NULL pointers. If you want to ensure that a parameter passed to a function is not NULL, you can pass by reference.
void func(int& i); // i cannot be NULL
References cannot always be replaced by pointers:
C a, b, c;
a = b - c;
If there is an operator-() for C, it either needs to receive its arguments:
by copy:
C operator-(C left, C right);
by address:
C operator-(C* left, C* right);
in which case the call becomes:
a = &b - &c;
(which already has a meaning in C)
or by using a new construct that has no equivalent in C. This became references in C++.
There are a variety of questions you can refer to concerning the use of references versus pointers.
This question already has answers here:
Two different values at the same memory address
(7 answers)
Closed 5 years ago.
Consider the following code:
I declare a new reference end assign it to value a via const_cast. Then I just increase the reference value print the addresses and values.
#include <iostream>
using namespace std;
int main()
{
const int a = 7;
int &b = const_cast<int&>(a);
++b;
cout<<"Addresses "<<&a<<" "<<&b<<endl;
cout<<"Values "<<a<<" "<<b<<endl;
}
//output
Addresses 0x7fff11f8e30c 0x7fff11f8e30c
Values 7 8
How can i have 2 different values in the same address??
Because modifying a variable declared to be const is undefined behavior, literally anything can happen.
Modifying a constant object gives undefined behaviour, so your program could (in principle) do anything.
One reason for leaving this behaviour undefined is to allow the optimisation of replacing a constant variable with its value (since you've stated that the value can never change). That's what is happening here: a is replaced with the value 7 at compile time, and so will keep that value whatever you try to do to it at run time.
Even though const_cast may remove constness from any pointer or reference, using the resulting pointer or reference to write to an object that was declared const invokes undefined behavior.
check out the example here for more illustration:
http://en.cppreference.com/w/cpp/language/const_cast
Any attempt to modify an object that is itself declared const by means of const_cast results in undefined behavior according to the ISO C++ Standard.
When the we refer "const object", it intends to say that the memory where the object is located may be write-protected. That is, a variable or expression of const type may denote an object stored in write-protected memory and any attempt to modify the object results in undefined behavior
EDIT: Refer this site for more info
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1994/N0571.asc
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ Reference, change the refered variable
I know that references in c++ are just pointers that get dereferenced for you when you use them. This question is about how to access the underlying pointer and change it.
Consider this code:
int x;
int& x_ref = x; //now equivalent to x
int* x_ptr = &x; //stores address of x
int* x_ref_ptr = &x_ref; //ALSO stores address of x
int&* x_ref_ptr_ref = ???; //what would this mean?
I'm trying to change where a reference points after initialization. I have no concern for type safety or proper practices. Does the c++ language have any tool to let me accomplish this?
There is no pointer to reference, it's ill-formed. A reference is an alias to an object. How would a pointer to an alias work?
Also, it's a feature of the language that a reference can't be reseated. A reseatable reference is a pointer.
This is not possible by design. By using a reference instead of a pointer, you decide to never change its target after declaration, with all entailing drawbacks and advantages (one of which is its "automatic dereferencing". Read the Wikipedia entry on references carefully.
You will need to switch to pointers.
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
int 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)