Temporary Variables: Chasing Temporaries Away - Help the compiler help you
(Page 5 of 5 )
Hopefully you will find it easy to keep an eye on the possible creation and destruction of temporary objects now. Of course it would be nice to have some support as well… you only need to forget once to add ‘&’ to your const function parameters and you are passing by value all of a sudden! You might think this won’t happen to you, but I found this happening to me when jumping between programming languages a lot. It was particularly noticeable when coming back from a scripting language like Python or LUA to C++.
Many scripting languages pass their variables around by reference as a default, so there is no special ‘reference’ operator like in C++. What if your compiler could tell you that you are passing by value when you probably don’t want this?
It is actually quite easy: make your copy constructor and assignment operator private by default. Now you won’t receive the ‘free’ bitwise copy constructor from the compiler, which it needs to create temporary objects. There are many situations where you want to be able to create copies of your class of course (when using STL containers for example), but I find it a good practice to make everything non-copyable by default and only explicitly allow for copies when needed, instead of the other way around.
class Skeleton {
private:
// copy ctor and assign operators are hidden by default.
Skeleton(Skeleton const&);
Skeleton& operator=(Skeleton const&);
};
Next time we'll take a walk on the wild side… detecting rvalues at runtime!
References [Meyers] – Scott Meyers
“Effective C++” – ISBN 0201924889
[Sutter] – Herb Sutter
“Exceptional C++” - ISBN 0201615622
[Niebler] – Eric Niebler
“Conditional Love: FOREACH Redux”
http://www.artima.com/cppsource/foreach.html
[Kernighan] – Brian Kernighan (interview)
http://www-2.cs.cmu.edu/~mihaib/kernighan-interview/
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |