C++ for Financial Mathematics (Chapman and HallCRC Financial Mathematics Series) by John Armstrong

C++ for Financial Mathematics (Chapman and HallCRC Financial Mathematics Series) by John Armstrong

Author:John Armstrong [Armstrong, John]
Language: eng
Format: azw3
Publisher: CRC Press
Published: 2017-01-05T16:00:00+00:00


shared_ptr works very well for most practical purposes but it does have the problem that if you have circular references between your data objects, then they will never get deleted. The cure for this is either to avoid circular references or to use an even smarter pointer library. In this book, we choose to simply avoid circular references.

11.7 Sharing data with references

A lot of what you can do with a pointer, you can do with a reference. For example, you can have a member variable which is a reference. If you store data by reference you save memory just as you do if you store data by pointer.

One advantage of using references rather than pointers is that you must initialise member variables which are references in the constructor. This means that the errors you can get from null pointers and uninitialised pointers just can’t happen with a reference.

However, using reference member variables is not normally as useful as choosing shared_ptr member variables. The reason is that owning a shared_ptr to an object means that you are guaranteed the object won’t be deleted until you no longer need it. On the other hand, if you use a reference, there’s a danger that someone else might delete your object.

Let’s give an example of why you shouldn’t normally use references as member variables. First we define a new Position class that contains a reference to an Instrument.

class PositionV3 {

public :

string trader ;

double quantity ;

Instrument & instrument ;

explicit PositionV3 ( Instrument & instrument );

};



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.