Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c++ > #7007
| From | Branimir Maksimovic <bmaxa@hotmail.com> |
|---|---|
| Newsgroups | comp.lang.c++ |
| Subject | Re: Const reference passing in constructor |
| Date | 2011-06-21 15:20 +0200 |
| Organization | solani.org |
| Message-ID | <itq5re$3p4$1@solani.org> (permalink) |
| References | <8cf0da8f-416c-434b-b876-293f1018b139@glegroupsg2000goo.googlegroups.com> |
On 06/21/2011 02:39 PM, Rahul Karnik wrote:
> Hi,
>
> I get a runtime error with the following code:
>
> #include<iostream>
>
> using namespace std;
>
> class B {
> const A& myA;
>
> public:
Try putting explicit constructor for B to get compile
error.
> B(const A& anA);
> int getn() const { return myA.getn(); };
> };
>
> B::B(const A& anA) : myA(anA) {}
>
> class C {
> const A& myA;
> const B& myB;
>
> public:
> C(const A& anA);
> int getn() const { return myB.getn(); };
> };
>
> C::C(const A& anA) : myA(anA), myB(myA) {}
Problem is here. B temporary is constructed from A reference
and then bound to const B reference .
Since temporary is destructed after constructing D object,
later on you have dangling reference.
Back to comp.lang.c++ | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Const reference passing in constructor Rahul Karnik <rahul@genebrew.com> - 2011-06-21 05:39 -0700 Re: Const reference passing in constructor Branimir Maksimovic <bmaxa@hotmail.com> - 2011-06-21 15:20 +0200 Re: Const reference passing in constructor "Paul" <pchristor@yahoo.co.uk> - 2011-06-21 14:47 +0100
csiph-web