An introduction to pointers and references in C++ (with elements of C++11 and C++14). The presentation introduces the readers to the concepts of pointers and references through the pragmatic need of writing a swap function between integers. Generic programming notions (e.g., type constructors) are adopted when useful for the explanation.
This Presentation gives you all knowledge about #CPointers, #PointersInC.
The given slides are as follows:
1. Introduction of Pointers.
2. Systems to create a pointer in C.
3. Valid Pointer Examples in C.
4. Graphical representation of address assigning in c using pointer.
5. 1st Sample program of pointers in C.
6. Types of Pointers
7. NULL Pointer in C (Types of Pointer)
8. void Pointer in C (Types of Pointer)
9. Wild Pointer in C (Types of Pointer)
10. Changing value of variable using pointer
11. Update and Access value of variable using pointer in example.
12. Types of format specifies to print address in different format.
13. Advantages of Pointer in C.
14. Disadvantages of Pointer in C.
15. Pointers with Array using Programs. #pointerwitharray
16. Another Example of #pointerwitharray.
17. Relationship Between Arrays and Pointers.
18. Relationship Between Arrays and Pointers explanation with diagram.
19. Pointers and String. #PointersAndString
20. Function with Array Parameters using pointers.
21. Passing Pointers to Function or Pointer argument function. #PointerWithFunction
This Presentation gives you all knowledge about #CPointers, #PointersInC.
The given slides are as follows:
1. Introduction of Pointers.
2. Systems to create a pointer in C.
3. Valid Pointer Examples in C.
4. Graphical representation of address assigning in c using pointer.
5. 1st Sample program of pointers in C.
6. Types of Pointers
7. NULL Pointer in C (Types of Pointer)
8. void Pointer in C (Types of Pointer)
9. Wild Pointer in C (Types of Pointer)
10. Changing value of variable using pointer
11. Update and Access value of variable using pointer in example.
12. Types of format specifies to print address in different format.
13. Advantages of Pointer in C.
14. Disadvantages of Pointer in C.
15. Pointers with Array using Programs. #pointerwitharray
16. Another Example of #pointerwitharray.
17. Relationship Between Arrays and Pointers.
18. Relationship Between Arrays and Pointers explanation with diagram.
19. Pointers and String. #PointersAndString
20. Function with Array Parameters using pointers.
21. Passing Pointers to Function or Pointer argument function. #PointerWithFunction
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address.
There are few important operations, which we will do with the help of pointers very frequently. (a) we define a pointer variable (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand.
Pratik Bakane C++ programs...............This are programs desingedby sy diploma student from Governement Polytecnic Thane.....programsare very easy alongwith coding andscreen shot of the output
A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. Like any variable or constant, you must declare a pointer before you can use it to store any variable address.
There are few important operations, which we will do with the help of pointers very frequently. (a) we define a pointer variable (b) assign the address of a variable to a pointer and (c) finally access the value at the address available in the pointer variable. This is done by using unary operator * that returns the value of the variable located at the address specified by its operand.
Pratik Bakane C++ programs...............This are programs desingedby sy diploma student from Governement Polytecnic Thane.....programsare very easy alongwith coding andscreen shot of the output
Pratik Bakane C++ programs...............This are programs desingedby sy diploma student from Governement Polytecnic Thane.....programsare very easy alongwith coding andscreen shot of the output
Pratik Bakane C++ programs...............This are programs desingedby sy diploma student from Governement Polytecnic Thane.....programsare very easy alongwith coding andscreen shot of the output
Pratik Bakane C++ programs...............This are programs desingedby sy diploma student from Governement Polytecnic Thane.....programsare very easy alongwith coding andscreen shot of the output
HexRaysCodeXplorer: object oriented RE for fun and profitAlex Matrosov
HexRaysCodeXplorer - Hex-Rays Decompiler plugin for easier code navigation. Here are the main features of the plugin:
- Automatic type REconstruction for C++ objects.
- C-tree graph visualization - a special tree-like structure representing a decompiled routine in c_itemt terms. Useful feature for understanding how the decompiler works.
- Navigation through virtual function calls in HexRays Pseudocode window.
- Object Explorer - useful interface for navigation through virtual tables (VTBL) structures.
In this presentation, the authors of HexRaysCodeXplorer will be discussing main functionality of the plugin and its application for reverse engineering. The authors will be presenting the algorithm for C++ type REconstruction. Also a special version of HexRaysCodeXplorer (H2HC edition) will be released with new features developed specially for H2Cconference. New features will be committed to GitHub from the stage.
Pointers are among C’s most powerful, yet most difficult concepts to master. Some tasks like dynamic memory allocation done only by using pointers. So it is essential to learn pointers.
Pointers are a type of variable, just like int, double, etc., except instead of storing a value, they store a memory address of another variable.
At the end of this lecture students should be able to;
Define the C pointers and its usage in computer programming.
Describe pointer declaration and initialization.
Apply C pointers for expressions.
Experiment on pointer operations.
Identify NULL pointer concept.
Experiment on pointer to pointer, pointer arrays, arrays with pointers and functions with pointers.
Apply taught concepts for writing programs.
This set of slides introduces the reader to a subset of the C++ Standard Library called the Standard Template Library (STL). The STL provides a collection of parameterized containers and algorithms, and it is the most successful example of an approach to programming called generic programming. In this presentation, we aim at studying the ideals and concepts of the STL by re-implementing small parts of the library. Specifically, we first show how we can discover requirements on types in order to devise generic algorithms. Then, we focus on how to make algorithms independent of containers through the pivotal abstraction of iterators. To this end, we replicate the standard algorithm for finding the minimum in a sequence (min_element), which we subsequently match with a custom forward iterator over intrusive linked lists of integers. Finally, we see how function objects can be used to customize containers and algorithms alike. This allows us to deepen our understanding of ordering relations, and, in particular, to introduce the concept of strict weak orderings.
This set of slides introduces the reader to the concept of regular types, i.e., user-defined types whose semantics closely resembles that of built-in types. The notion of regular types proved crucial for the development of the C++ Standard Template Library, and it is currently employed in next-gen C++ libraries such as Eric Niebler's range-v3. The presentation serves as a gentle introduction to the topic, and discusses which requirements must be satisfied for a type to be regular. In particular, the concept of equality-preserving copy and assignment is presented, as well as how to define ordering relations that satisfy the requirements of strictness, transitivity and comparability (i.e., that adhere to the trichotomy law).
This set of slides introduces the reader to the concept of resource wrappers, i.e., classes that are responsible for the correct handling of resources of some kind (e.g., memory). In particular, the presentation discusses the design and implementation of a simplified version of std::vector for the specific case of integer elements. In this regard, we first discuss the fundamental role of destructors as a deterministic, general-purpose undo mechanism. Second, we notice that providing an explicit destructor entails the need of a consequent explicit implementation for the copy constructor and copy assignment operator. We conclude with the formulation of the so-called "rule of three".
This set of slides introduces the reader to the basics of memory management in C++ (with elements of C++11 and C++14). Specifically, after presenting the essential idea of memory segmentation, the presentation contrasts automatic and dynamic objects. To this extent the critical issue of memory leaks is introduced. It follows a discussion on the more advanced topics, such as owning and non-owning (i.e., observer) pointers, as well as dynamic arrays and structures.
This set of slides introduces the reader to the concept of operator overloading for user-defined types in C++ (with elements of C++11 and C++14). The exemplary case of the complex class is introduced. It follows a discussion on how to implement mixed-mode arithmetic, which requires mixing member and non-member operator functions. Moreover, the technical tool of friend functions and access functions is discussed.
This set of slides introduces the reader to the concept of multidimensional arrays in C++ (with elements of C++11 and C++14). The true nature of multidimensional arrays is discussed by means of an intermediate type alias. The pheonomenon of array-to-pointer decay and pointer arithmetic is then generalized to arrays of arrays. The presentation proceeds with a discussion on how to pass multidimensional arrays to functions.
This set of slides introduces the reader to the concept of arrays in C++ (with elements of C++11 and C++14). After presenting the array data type, the concept of array-to-pointer decay is introduced. The presentation proceeds with a discussion on how to pass arrays to functions. To this extent, the reader is guided to the use of bounded ranges as the first step towards the use of the Standard Template Library (STL).
Spring MVC - Wiring the different layersIlio Catallo
The presentation focuses on the problem of wiring the different layers of a Spring MVC Web application. More precisely, the presentation explains how to wire the presentation layer (made of Spring MVC controllers) with the service and persistence objects. To this end, the slides first explain how to create the so called back-end (a.k.a. root) container, which will host the persistence and the service objects. Second, the @Repository and @Service annotations are introduced, which permit the framework to auto-discover the application beans. Finally, it is discussed how to wire such beans, through the usage of either the Spring-specific @Autowired annotation or the JEE @Inject annotation.
This set of slides introduces the basic concepts of Java development. First, the difference between Java as the programming language and Java as a platform is stated. Then, the different Java platforms are presented, with a particular interest in Java Standard Edition and Java Enterprise Edition. With respect to the latter, the roles and differences between the many JEE containers are discussed.
How to process request parameters with the Spring MVC framework. Namely, the presentation tackles the three primary concerns when dealing with request parameters: data binding, data buffering and data validation. To this end, the Bean Validation API (JSR-303) is discussed, and the concept of MessageSource for localized error messages is introduced. Moreover, The Post/Redirect/Get (PRG) pattern is presented along with a possible implementation strategy.
An introduction to the basics of the Spring MVC Web framework. The concepts of front controller, controller (handler), model and view are introduced. The whole processing pipeline is discussed, with an in-depth description of the HandlerMapping and ViewResolver strategy interfaces. The alternative representations of the Model (Map, Model and ModelMap) are presented.
This set of slides deals with the problem of building robust Web applications by isolating different areas of concern into different layers. The typical four-layer architecture is presented (consisting of the presentation, service and persistence layer, as well as of the domain model) along with an in-depth discussion on the role and responsibilities of each single layer.
Introduzione al concetto di oggetto nel modello della memoria del C++ e ai suoi possibile tempi di vita (temporaneo, automatico, dinamico, ...). Relazione tra il tempo di vita e la visibilità (scope) di un oggetto. Gestione degli oggetti dinamici per tipi primitivi, strutture e array mediante l'utilizzo di puntatori (raw pointers).
Introduzione agli Array in C++. Argomenti trattati: decadimento a puntatore di un array; conseguenze del meccanismo di decadimento sul passaggio di array a funzioni; array multidimensionali e il concetto di puntatore ad array; come passare array multidimensionali a funzioni; gli iteratori come generalizzazione di un puntatore ad elemento di un array ed una breve scorsa di come usare gli iteratori con gli algoritmi standard (e.g., std::copy) del C++.
Introduzione ai puntatori e ai riferimenti in C++. Viene presentato il problema dello swap, come esempio motivante per l'introduzione della semantica di riferimento. Si procede con l'introduzione del concetto di puntatore, a cui segue una spiegazione dei basilare operatori di referenziazione e dereferenziazione. Il problema dello swap viene risolto mediante puntatori. Si procede con l'introduzione dei riferimenti, come alias di variabili esistenti. Il problema dello swap viene in ultimo risolto mediante riferimenti.
An introduction to the Java Persistence API 2.x (JPA). Namely, this set of slides first introduces the problem of impedance mismatch between the object model and the relation model. Then, the EntityManager's public interface is discussed, together with the parallelism between a persistence context and a L1 cache. The issue of encapsulating the different application's use cases (which are exposed by the service objects) is solved by means of the @Transactional annotation, which provides a declarative way of demarcating the application's transactional boundaries. It follows an in-depth explanation on how to integrate a local, container-managed EntityManager within an existing Spring MVC application, so as to correctly support the propagation of the persistence context throughout the different beans involved in the same transaction. We then turn our attention to the problem of mapping relationships, thus introducing the @OneToMany, @ManyToMany and @OneToOne annotations. The additional topics of how to cascade operations and how to support lazy loading are covered as well. The presentation concludes with a discussion on how to use both the Criteria and Query API (and JPQL) to query the underlying database.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
4. Swapping integers
Assume that we are wri-ng a program in which we o3en need to
swap two integers
┌──────────────────┐
│ │
│ ▼
┌───┐ ┌───┐
a:│ 2 │int b:│ 5 │int
└───┘ └───┘
▲ │
│ │
└──────────────────┘
9. First a(empt
At swap_int invoca*on:
• The values in a and b get copied into the local variables x and y
• The values in x and y get swapped, but...
• The values in a and b remain untouched
10. First a(empt
void swap_int(int x, int y) {
...
}
int main() {
int a = 2, b = 5;
swap_int(a, b); // x and y are copies of a and b
// hence, a and b remain unchanged
}
11. The swap problem
We conclude that it is not possible to write the swap_int
func1on if we pass parameters by value
14. Memory model
In C++, memory is modeled as a sequence of memory cells, where
each cell is of size 1 byte
┌──────┬──────┬──────┬──────┐
... │ │ │ │ │ ...
└──────┴──────┴──────┴──────┘
◀─────▶
1 byte
15. Memory model
Each memory cell is associated with a unique memory address
┌──────┬──────┬──────┬──────┐
... │ │ │ │ │ ...
└──────┴──────┴──────┴──────┘
0x7345
16. Memory model
Memory addresses are nothing more than numbers1
┌──────┬──────┬──────┬──────┐
... │ │ │ │ │ ...
└──────┴──────┴──────┴──────┘
0x7345
1
The 0x prefix is to say that the numbers are given in hexadecimal nota6on
17. Memory model
Given a cell, its address is obtained as the address of the previous
one plus one
┌──────┬──────┬──────┬──────┐
... │ │ │ │ │ ...
└──────┴──────┴──────┴──────┘
0x7345 0x7346 0x7347
18. Memory model
This assures that:
• Every memory cell has its own unique address
• Given a cell, it is possible to compute the address of its
neighborhood
19. Variable iden+fiers
We usually do not care about where values are stored
int a
◀───────────▶
┌──────┬──────┬──────┬──────┐
... │//////│//////│ │ │ ...
└──────┴──────┴──────┴──────┘
0x7345 0x7346 0x7347
20. Variable iden+fiers
We simply manipulate values by referring to the iden%fier of the
corresponding variable
int a = 3;
a = a + 7; // we do not know where `a` is stored in memory
21. Addresses
However, there might be situa2ons in which we would like to refer
to the in-memory loca-on of a value, rather than to the value itself
22. The ampersand
In order to manipulate the address of a variable, we prefix the
variable iden8fier with the ampersand symbol &
23. The ampersand
int a = 5;
std::cout << "value of a: " << a
<< std::endl;
std::cout << "address of a: " << &a
<< std::endl;
24. The address-of operator
When the ampersand symbol & precedes an expression2
, it plays
the role of a unary operator (the address-of operator)
int a = 7;
std::cout << &a; // conceptually: address_of(a);
2
Note that there exist expressions on which it is not possible to apply the address-of operator
25. The address-of operator
Note that if a value occupies more than one memory cell, the
address-of operator returns the address of the first memory cell
int a
◀───────────▶
┌──────┬──────┬──────┬──────┐
... │//////│//////│ │ │ ...
└──────┴──────┴──────┴──────┘
0x7345 0x7346 0x7347
▲
│
│
&a
26. A formal defini.on of copy
A copy is a something that is equal to the original but not iden)cal
to it
int a = 7;
int b = a;
a == b; // b is equal to a (they both contain 7)
&a != &b; // b is not a (they live in different memory locations)
31. Pointer to int
The data type of a variable storing the address of an int is int*.
Such a data type is called pointer to int
int* address_of_a = &a
32. Pointers
Variables that store addresses are called pointers
It is possible to create pointers to any data type3
, for built-in and
user-defined types alike
3
As long as the data type is at least of size 1 byte
33. For any data type T, T* is the data type pointer to T
34. Examples
int* a; // pointer to int
char* b; // pointer to char
float* c; // pointer to float
int** d; // pointer to pointer to int
36. Pointers as type constructors
The * symbol plays the role of a type constructor
A type constructor is a func0on that takes as input some type T
and returns some other type T'
48. Dereferencing
The dereference operator * makes possible to access the content
pointed to by a pointer4
int* ptr = ...
std::cout << "the value pointed to is: " << *ptr;
4
The dereference operator is also called the indirec'on operator
49. Dereferencing
The expression *ptr reads "the value pointed to by ptr"
int* ptr = ...
std::cout << "the value pointed to is: " << *ptr;
51. Dereferencing
In other words, the expression *ptr may also appear on the le4-
hand side of the assignment operator
int* ptr = ...
*ptr = 7;
int b = 5 + *ptr; // b contains 12
52. Same symbol, two meanings
// * is a type constructor
int* ptr_a = &a;
// * is an operator
std::cout << "pointed value: " << *ptr_a;
53. Trivia 1: What's the output?
int a = 7;
int* ptr = &a;
*ptr = 12;
std::cout << *ptr << std::endl;
std::cout << a << std::endl;
54. Trivia 2: What's the output?
int a = 7;
int* ptr = &a;
std::cout << &ptr << std::endl;
std::cout << &a << std::endl;
57. The "box" metaphor
Just as a vector is a container of many elements, we can say that a
pointer is a container of one element5
5
More formally, the similarity holds because both of them are functors
58. The "box" metaphor
// we put some values in the container
std::vector<int> v = {1, 2, 3, 4, 5};
// accessing the 3rd element
// in the container
std::cout << v[2];
59. The "box" metaphor
// we "put" a value in the container
int* p = &a;
// accessing the only element
// in the container
std::cout << *p;
62. Unini$alized pointers
As with any local variable, it is not possible to foresee the value of
unini6alized pointers
int* ptr; // uninitialized pointer
63. Unini$alized pointers
The pointer may hold any value. Such a value will be erroneously
intended as the address of a pointed value
int* ptr; // uninitialized pointer
64. Unini$alized pointers
There does not exist any way to understand whether a pointer is in
fact poin4ng to a valid value
int* ptr; // uninitialized pointer
65. Null pointers
We would like to ini#alize pointers even in the absence of a
sensible value
int* ptr = ???;
66. Null pointers
Pointers can be ini-alized to null in order to indicate that the
pointer is currently not poin-ng to any valid value6
int* ptr = nullptr; // since C++11
int* ptr = NULL; // C++03
6
In terms of the box metaphor, this amounts to no4fying that the container is empty
67. Solving the swap problem
Can we use pointers to write a working version of the swap_int
func4on?
68. Idea: passing to swap_int the variable addresses (as
opposed to their values)
72. swap_int with pointers
At swap_int invoca*on:
• The addresses of a and b get copied into the pointers x and y
(which are local to swap_int)
• The values pointed to by x and y (i.e., a and b) get swapped
• At the end of swap_int, x and y get destroyed
73. How to invoke swap_int?
int main() {
int a = 2;
int b = 5;
swap_int(???, ???);
}
74. How to invoke swap_int?
int main() {
int a = 2;
int b = 5;
swap_int(&a, &b);
}
75. Passing by address
If a func(on receives addresses in place of values, we say that
parameter are passed by address
void swap_int(int* x, int* y);
76. Passing by address
However, since we pass address copies, passing by address is just a
par6cular case of passing by value
void swap_int(int* x, int* y);
77. Passing by address
Passing by address allows...
• propaga'ng altera'ons in the callee func'on also in the calling
func'on
• rapidly accessing big data, since we copy its address as opposed
to its value
81. Iden%fiers
When declaring a variable, we need to specify its data type and
iden*fier
Both these aspects cannot be modified later on in the program
82. Iden%fier aliases
However, C++ allows introducing addi5onal iden5fiers (aliases) for
a variables any5me in the code
int a = 5;
int& b = a; // b is a new identifier (alias) for a
83. Iden%fier aliases
b is an alias for a, and its data type is int&
int a = 5;
int& b = a; // b is a new identifier (alias) for a
84. References
In C++, iden*fier aliases are called references7
int a = 5;
int& b = a; // b is a reference to a
7
Star'ng from C++11, references have been renamed lvalue references
85. For a data type T, T& is the data type reference to T
86. Examples
int& a = b; // a is an alias for b (where b is of type int)
float& c = d // c is an alias for d (where d is of type float)
int& e = b; // e is an alias for b, hence an alias for a
int*& f = g; // f is an alias for g (where g is of type int*)
87. Trivia 1: what's the output?
int a = 5;
int& b = a;
b = 7;
std::cout << a;
88. Trivia 1: what's the output?
int a = 5;
int& b = a; // b is a new name for a
b = 7;
std::cout << a; // the output will be 7
89. Aliases are indis+nguishable
Once ini'alized, using either the new or the old iden'fier is a
ma7er of indifference
int a = 5;
int& b = a; // b is a new name for a
// using b is the same as using a (and vice-versa)
std::cout << b;
90. Aliases are indis+nguishable
That is, the reference is the referent8
int a = 5;
int& b = a; // b is a new name for a
// using b is the same as using a (and vice-versa)
std::cout << b;
8
While holding conceptually, the C++11 specifica8on qualifies the reference and the referent as two different
en88es
91. & as a type constructor
As with *, also & can be intended as a type constructor
92. & as a type constructor
Construc)ng the type "reference to float"
• Input type: float
• Type constructor: &
• Output type: float&
93. Same symbol, two meanings
int a = 5;
// & is a type constructor
int& b = a;
// & is an operator
std::cout << &a;
94. Solving the swap problem
Can we use references to write a working version of the swap_int
func3on?
99. swap_int with references
Note that the func,on body is the same as in our first a5empt
void swap_int(int& x, int& y) {
int temp = x;
x = y;
y = temp;
}
100. How to invoke swap_int?
int main() {
int a = 2;
int b = 5;
swap_int(???, ???);
}
101. How to invoke swap_int?
int main() {
int a = 2;
int b = 5;
swap_int(a, b);
}
102. How to invoke swap_int?
Note that we invoke swap_int as any other func3on
int main() {
int a = 2;
int b = 5;
swap_int(a, b);
}
103. swap_int with references
References allow us to write swap_int in an easy and safe
manner
• Easy: we do not need to use the dereference operator *
everywhere
• Safe: the program will not compile if we try to pass nullptr or
temporary values
104. Passing by reference
If a func(on receives iden%fier aliases in place of values, we say
that parameter are passed by reference
void swap_int(int& x, int& y);
107. References are not assignable
References can be ini#alized, but not (re)-assigned
int a = 5;
int& b; // b is an alias for what?
b = a;
108. Does it work?
void countdown(int& number) {
std::cout << number << std::endl;
if (number != 0)
countdown(number - 1);
}
109. The compile-,me error
Here's the error:
error: invalid initialization of non-const reference of
type 'int&' from an rvalue of type 'int'
110. The compile-,me error
We can safely replace the term rvalue with temporary:
error: invalid initialization of non-const reference of
type 'int&' from a temporary of type 'int'
111. The compile-,me error
The temporary the error is referring to is number - 1
void countdown(int& number) {
std::cout << number << std::endl;
if (number != 0)
countdown(number - 1);
}
112. Reference-to-const
The correct version reads:
void countdown(int const& number) {
std::cout << number << std::endl;
if (number != 0)
countdown(number - 1);
}
113. Reference-to-const
Only constant references can bind to temporary values
void countdown(int const& number) {
std::cout << number << std::endl;
if (number != 0)
countdown(number - 1);
}
114. Reference-to-const
This is why the input parameter number has to be of type int
const&, rather than int&
void countdown(int const& number) {
std::cout << number << std::endl;
if (number != 0)
countdown(number - 1);
}
116. Dangling references
Although it compiles, the add func2on causes an undefined
behavior
double& add(double x, double y) {
double z = x + y;
return z;
}
117. Dangling references
This is because we are returning an alias for z, which will be
destroyed as soon as we exit the func7on
double& add(double x, double y) {
double z = x + y;
return z;
}
118. Dangling references
In other words, the add func0on returns a dangling reference, that
is, a reference for a non-exis0ng object
double& add(double x, double y) {
double z = x + y;
return z;
}
int main() {
double r = add(5, 3);
std::cout << r;
}
119. Dangling references
Although this seems trivial when presented in contrived examples,
this is an easy mistake to make when wri9ng class' ge;ers and
se;ers
121. Bibliography
• S. B. Lippman, J. Lajoie, B. E. Moo, C++ Primer (5th Ed.)
• B. Stroustrup, The C++ Programming Language (4th Ed.)
• R. Lafore, Object Oriented Programming in C++ (4th Ed.)
• C++FAQ, SecJon 8