Docsity

Lab 4: Pointers, References and Their Uses in C++, Slides of Design

Toggle sidebar
bg1
Programming in C++
Lab 4 – pointers, references and how to use them
Pointers
C++ allows programmer to access memory directly by using pointers. Pointer is address to a
memory socket that contains some data or from where some data begins. In case of a pointer one
must consider two different values: address and data that it is pointing to. Note that in case of
defining a pointer by default no memory is allocated. That is something a programmer must do
by himself. If a pointer points to an arbitrary memory slot then in case of reading or writing that
data operating systems with memory protection stop the program (error messages like
segmentation fault, page fault, general protection fault).
Following table represents an example of memory. First row shows memory addresses and second
one its corresponding values. Every memory slot contains one byte. In case of larger values, the
order of reading the bytes is important. In given example bytes are read from left to right. For
example if two memory slots in sequence contain bytes 2 and 1 then they may contain two-byte
integer 258 = (256*1 + 2). For more info on byte order: http://en.wikipedia.org/wiki/Little_endian.
1
2
3
4
5
6
7
8
9
10
11
13
14
15
16
17
18
19
20
34
4A
11
B5
FF
3
23
F0
C0
20
6D
83
0
7
1
34
22
BA
D
An asterisk is used to define a pointer. It is also used later to access the data from given memory
address. An example of defining a pointer is given below. NB! Given code will not run, becasue it
is not allowed to access arbitrary memory slots. Take it as an example.
unsigned short *somenumber = 15; /* Saving memory address */
cout << somenumber; /* Returns 15 */
cout << *somenumber; /* Returns 263 (why?) */
somenumber = 14; /* New address. Value of *somenumber now?
*/
*somenumber = 1; /* Change value. */
somenumber = 15; /* Value of *somenumber ? */
When to use pointers?
Using pointers is more complicated than defining regular variables, therefore it is reasonable to
use them when it brings about higher efficiency or better design. Before using a pointer one must
check that it has a value and it isn't null pointer. (C++11 adds keyword nullptr, before value 0
pf3
pf4
pf5

Partial preview of the text

Download Lab 4: Pointers, References and Their Uses in C++ and more Slides Design in PDF only on Docsity!

Programming in C++

Lab 4 – pointers, references and how to use them

Pointers

C++ allows programmer to access memory directly by using pointers. Pointer is address to a memory socket that contains some data or from where some data begins. In case of a pointer one must consider two different values: address and data that it is pointing to. Note that in case of defining a pointer by default no memory is allocated. That is something a programmer must do by himself. If a pointer points to an arbitrary memory slot then in case of reading or writing that data operating systems with memory protection stop the program (error messages like segmentation fault , page fault , general protection fault ). Following table represents an example of memory. First row shows memory addresses and second one its corresponding values. Every memory slot contains one byte. In case of larger values, the order of reading the bytes is important. In given example bytes are read from left to right. For example if two memory slots in sequence contain bytes 2 and 1 then they may contain two-byte integer 258 = (256*1 + 2). For more info on byte order: http://en.wikipedia.org/wiki/Little_endian. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 34 4A 11 B5 FF 3 23 F0 C0 20 6D 30 83 0 7 1 34 22 BA D An asterisk is used to define a pointer. It is also used later to access the data from given memory address. An example of defining a pointer is given below. NB! Given code will not run, becasue it is not allowed to access arbitrary memory slots. Take it as an example. unsigned short somenumber = 15; / Saving memory address / cout << somenumber; / Returns 15 */ cout << somenumber; / Returns 263 (why?) / somenumber = 14; / New address. Value of *somenumber now? */ somenumber = 1; / Change value. / somenumber = 15; / Value of *somenumber? */

When to use pointers?

Using pointers is more complicated than defining regular variables, therefore it is reasonable to use them when it brings about higher efficiency or better design. Before using a pointer one must check that it has a value and it isn't null pointer. (C++11 adds keyword nullptr, before value 0

or constant NULL was used). Additionally, one must release all the memory allocated for pointers, otherwise it „leaks” and reduces total available memory.

References

References were added to C++ to offer some gains of pointers without the dangers involved. Reference is basically new name to a variable or object by which it can be used. Reference by itself does not have it's own data nor address – it only references already existing object. To define a reference, one must use an ampersand. Simple use of a reference: int a = 5, b = 9; // define variables a and b int& refToA = a; // refToA is new name to variable a cout << a << "," << refToA << "," << b; // returns 5,5, a = 7; // change a value cout << a << "," << refToA << "," << b; // returns 7,7, refToA = 11; // change refToA value cout << a << "," << refToA << "," << b; // returns 11,11,

When to use references?

If you need to use same variables or objects in many places then consider using references where possible and when not (to differentiate between existing object from one not yet created), then pointers. Use references everywhere where it helps to reduce excessive copying of data.

Allocating and releasing data for pointers: operators new and delete

Operator new calculates how much memory is needed for given object, allocates it and returns pointer to beginning of the memory slot int *a = new int; // call without constructor Point2 *v = new Point2 {}; // parameters may be added to the constructor If an object is a pointer then operator - > is used to access it's data cout << "Coordinates are " << v - > x << " and " << v - > y << "." << endl; Allocating memory may fail, therefore it is necessary to check whether or not it succeeded. Values created by keyword new must be released by using delete. NB! In case of allocating memory for several objects with operator new[] then for release delete[] must be used. delete a;

recommended, because then there will be less copying of data. Also pointers or references are needed when function is expected to change the data given to it.

Pointers and references as function return values

Take care when a function returns a pointer or a reference. Examples will be brought, but first let's explain the scope of a variable. Ordinary variable is „alive” only within its scope – inside a structure or part of a code in which it was defined. When structure is destroyed or the part of the code ends, the variable is destroyed. Variable a is an ordinary variable for which memory is allocated and released automatically. Upon returning from function a is destroyed and upon leaving the cycle i is destroyed. Function arvuta_midagi returns integer a. Since the function returns a value then a is copied for the calling function. string& arvuta_teisiti () { string s = "C++"; return s; } Function arvuta_teisiti tries to return reference to a local variable. This is most probably wrong and usually produces a compiler warning. Memory for variable s is released and returned reference is left to point to nowhere. When returning a reference, one must make sure that it is valid after returning from the function. Point2* tee_uus_tipp () { Point2* tee_uus_tipp2 () { Point2 v; Point2* v = new Point2 {}; return &v; // WRONG! return v; } } Function tee_uus_tipp creates a point with as an ordinary variable and returns its address (note

the operator &, that is responsible for returning memory address of an object written to the right of it). This kind of action brings about same dangers as with references. Much bigger problem is that here compiler will not warn us, because pointer pointing nowhere is totally legal. Function tee_uus_tipp2 shows how to fulfill similar task correctly. Note that after using this kind of approach the programmer is responsible of relasing the memory. For that, correct function is for example: void vabasta_tipp (Point2 v) { if (v) delete v; } Note that one could aslo do like in following example. Pointer returned by the function is valid as long as Someclass instance on which get_something was called exists). class Someclass { int a; int get_something () { return &a; } };

How does C++11 change the use of pointers and references?

C++11 complements the use of pointers and references in several ways. All upgrades will not be covered in labs. Following materials are for those who are interested in more possibilities of C++. Move constructor and move assignment operator Additionally to constructor, destructor, copy constructor and assignment operator the developer can now also use move constructor and move assignment which avoid copying. This is useful in cases where copying is not needed and moving is enough. SomeObject a, b, c; c = a + b; If SomeObject class had ordinary assignment operator then in memory additional variable is made for addition a + b and it's value is copyied into c. If the class has move assignment operator then copying is avoided and less work is done. Read more: http://stackoverflow.com/questions/4782757/rule-of-three-becomes-rule-of-five-with-c Alternative: http://flamingdangerzone.com/cxx11/2012/08/15/rule-of-zero.html