Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- In C, the primary way to accomplish such behavior is to pass in a pointer to the variable instead
- of the variable itself. The only problem with this approach is that it brings the messiness of pointer
- syntax into what is really a simple task. In C++, there is an explicit mechanism for “pass-byreference.”
- Attaching & to a type indicates that the variable is a reference. It is still used as though
- it was a normal variable, but behind the scenes, it is really a pointer to the original variable. Below
- are two implementations of an addOne() function. The fi rst will have no effect on the variable that
- is passed in because it is passed by value. The second uses a reference and thus changes the original
- variable.
- void addOne(int i)
- {
- i++; // Has no real effect because this is a copy of the original
- }
- void addOne(int& i)
- {
- i++; // Actually changes the original variable
- }
- The syntax for the call to the addOne() function with an integer reference is no different than if the
- function just took an integer.
- int myInt = 7;
- addOne(myInt);
- There is a subtle difference between the two addOne() implementations. The
- version using pass-by-value will accept constants without a problem; for example
- “addOne(3);” is legal. However, doing the same with the pass-by-reference
- version of addOne() will result in a compiler error. This can be solved by using
- rvalue references, which are explained in Chapter 9.
- Exceptions
- C++ is a very fl exible language, but not a particularly safe one. The compiler will let you write
- code that scribbles on random memory addresses or tries to divide by zero (computers don’t deal
- well with infi nity). One of the language features that attempts to add a degree of safety back to the
- language is exceptions.
- An exception is an unexpected situation. For example, if you are writing a function that retrieves a
- web page, several things could go wrong. The Internet host that contains the page might be down,
- the page might come back blank, or the connection could be lost. In many programming languages,
- you would handle this situation by returning a special value from the function, such as nullptr
- (NULL in pre-C++11) or an error code. Exceptions provide a much better mechanism for dealing with
- problems.
- Exceptions come with some new terminology. When a piece of code detects an exceptional
- situation, it throws an exception. Another piece of code catches the exception and takes appropriate
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement