Advertisement
Guest User

Untitled

a guest
Jan 17th, 2020
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.41 KB | None | 0 0
  1. In C, the primary way to accomplish such behavior is to pass in a pointer to the variable instead
  2. of the variable itself. The only problem with this approach is that it brings the messiness of pointer
  3. syntax into what is really a simple task. In C++, there is an explicit mechanism for “pass-byreference.”
  4. Attaching & to a type indicates that the variable is a reference. It is still used as though
  5. it was a normal variable, but behind the scenes, it is really a pointer to the original variable. Below
  6. are two implementations of an addOne() function. The fi rst will have no effect on the variable that
  7. is passed in because it is passed by value. The second uses a reference and thus changes the original
  8. variable.
  9. void addOne(int i)
  10. {
  11. i++; // Has no real effect because this is a copy of the original
  12. }
  13. void addOne(int& i)
  14. {
  15. i++; // Actually changes the original variable
  16. }
  17. The syntax for the call to the addOne() function with an integer reference is no different than if the
  18. function just took an integer.
  19. int myInt = 7;
  20. addOne(myInt);
  21. There is a subtle difference between the two addOne() implementations. The
  22. version using pass-by-value will accept constants without a problem; for example
  23. “addOne(3);” is legal. However, doing the same with the pass-by-reference
  24. version of addOne() will result in a compiler error. This can be solved by using
  25. rvalue references, which are explained in Chapter 9.
  26. Exceptions
  27. C++ is a very fl exible language, but not a particularly safe one. The compiler will let you write
  28. code that scribbles on random memory addresses or tries to divide by zero (computers don’t deal
  29. well with infi nity). One of the language features that attempts to add a degree of safety back to the
  30. language is exceptions.
  31. An exception is an unexpected situation. For example, if you are writing a function that retrieves a
  32. web page, several things could go wrong. The Internet host that contains the page might be down,
  33. the page might come back blank, or the connection could be lost. In many programming languages,
  34. you would handle this situation by returning a special value from the function, such as nullptr
  35. (NULL in pre-C++11) or an error code. Exceptions provide a much better mechanism for dealing with
  36. problems.
  37. Exceptions come with some new terminology. When a piece of code detects an exceptional
  38. 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