Path: reader1.panix.com!panix!newsfeed-00.mathworks.com!kanaga.switch.ch!switch.ch!news-2.dfn.de!news.dfn.de!feeder.erje.net!newsfeed.xs4all.nl!newsfeed6.news.xs4all.nl!xs4all!post2.news.xs4all.nl!newszilla.xs4all.nl!not-for-mail From: Bart van Ingen Schenau Newsgroups: comp.lang.c++ Subject: Re: return references from templates Date: Sun, 27 Mar 2011 16:00:02 +0200 Organization: No organisation in particular Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain User-Agent: Web-News v.1.6.4 (by Terence Yim) Lines: 47 NNTP-Posting-Host: 83.160.243.23 X-Trace: 1301234461 dreader21.news.xs4all.nl 4349 [::ffff:83.160.243.23]:37355 Xref: panix comp.lang.c++:1082567 Ruben Safir Wrote: > I added the references because the Template > Textbook seemed to be big on it, and I thought there might be an > advantage when using the methods in certain syntactic situations, similar > to the operator[]. But since I'm now returning pointers to values rather > than values themselves, maybe it is redundant. > > Is there any practical difference between returning a reference to a > pointer rather than a pointer itself? There is a very big practical difference. When you return a reference (to anything, including pointers), you must ensure that the variable/object that the reference refers to remains valid as long as the reference is around. For returning a reference from a function, this means that you can not return a reference to a local variable, because that local variable will be destroyed even before the caller could lay its hands on the reference. When you return a pointer, the compiler will make a copy of the address value stored in the pointer and returns that value. It is still your responsibility to ensure the address value is the address of an existing object or variable (so not the address of a local variable), but that is harder to get wrong. References are typically used when you don't want the overhead of copying around (potentially) large objects, but it comes with the responsibility on you to ensure those objects stay around long enough. This is used very often with function parameters, because the caller is required not to clean-up any function arguments until the callee has returned. For return values it is used less often, because you have to return something that existed before the function call (or something allocated dynamically inside the function, but then returning a pointer is better) in order to meet the responsibility of ensuring the object stays around long enough. The reason why references are used so much in combination with templates, is because it is unknown how costly it will be to copy the template parameters around and the designers assume the worst. However, when you know how large the function argument or return value will be (e.g. it is a pointer or an index), then you also know how costly it is to copy it around and you can base your use of references on that knowledge. Bart v Ingen Schenau