| re: simple reference question
[color=blue]
> A basic question, inspired by code in 'exceptional c++ style' pg. 124:
>
> The example code illustrates accessor functions instead of making data
> public.
> To paraphrase:
>
> Class X {
> public:
> T1& UseT1() {return t1_;}
> private:
> T1 t1_;
> };
>
> I would have written: T1 UseT1() {return t1_;}, so my question is:
>
> t1_ is just returned (as a value?) so what does the '&' do in the return
> type definition? Does it really return a reference to the internal
> value? What are the ownership/lifetime implications of 'T1 &' versus
> 'T1' ?[/color]
1. The whole point of the declared function to enable something like this:
X x;
T1& t = x.UseT1(); // get value;
x.UseT1() = T(); // set value;
t = T(); // another way to set value;
Had the return type be a plain T1, you won't be able to set the value.
2. Now since X::t1_ is owned by X, its life time relies on X, so
X& x_ref = *(new X);
T1& t = x_ref.UseT1();
delete &x_ref;
t = T(); // funny things happen here because t references to no object
now
3. For completion, it is nice to add one more UseT1 for const use:
const T1& UseT1() const;
so to enable something like this:
const X x;
T1 t = x.UseT1(); // OK, from const T1& to T1
x.UseT1() = T(); // ERROR, cannot assign a constant
[color=blue]
>
> cheers
>
> shaun[/color] |