03.12.2012 Views

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

C++ for Scientists - Technische Universität Dresden

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

2.11. REAL-WORLD EXAMPLE: MATRIX INVERSION 53<br />

Feature Pointers References<br />

Referring defined location - +<br />

Mandatory initialisation - +<br />

Avoidance of memory leaks - +<br />

Object-like notation - +<br />

Memory management + -<br />

Adress calculation + -<br />

Table 2.2: comparison between pointers and references<br />

For short, references are not idiot-proof but much less error-prone than pointers. Pointers<br />

should be only used when dealing with dynamic memory and even then one should do this via<br />

well-tested types or encapsulate the pointer within a class.<br />

2.10.4 Do Not Refer Outdated Data<br />

Variables in functions are only valid within this function, <strong>for</strong> instance:<br />

double& square ref(double d) // DO NOT!<br />

{<br />

double s= d ∗ d;<br />

return s;<br />

}<br />

The variable s is not valid anymore after the function is finished. If you are lucky the memory<br />

where s was stored is not overwritten yet. But this is nothing one can count on. Good compilers<br />

will warn you that you are referring local variable. Sadly enough we have seen examples in web<br />

tutorial that do this!<br />

The same applies correspondingly to pointers:<br />

double∗ square ptr(double d) // DO NOT!<br />

{<br />

double s= d ∗ d;<br />

return &s;<br />

}<br />

This is as wrong as it is <strong>for</strong> references.<br />

There are cases where functions, esp. member functions return references and addresses and<br />

the destruction order of object impedes the invalidation of references, 24 cf. § ??.<br />

2.11 Real-world example: matrix inversion<br />

TODO: I am not sure anymore if this is very good here. I still think we should propagate<br />

abstraction and demonstrate how to develop reusable software but the section feels now a bit<br />

misplaced. At the beginning of the next chapter is not much better. Maybe a good intro<br />

paragraph saves the situation.<br />

24 Un<strong>for</strong>tunately there are ways to circumvent this and an exception to this rule.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!