Overloading operator []

G

Guest

I have not posted to comp.lang.c++ (or comp.lang.c++.moderated)
before. In general when I have a C++ question I look for answers in
"The C++ Programming Language, Third Edition" by Stroustrup.
However, I've come upon a question that I can neither answer from
"The Book" or a Google search (so yes, at least I RTFBed). I'm
hoping that someone in this news group might know the answer.

Overloading the [] Operator

Say I want to develop a class that supports the overloaded []
operator and reads and writes the "int" type. I thought that the
way this was done was:

class MyClass
{
//...
// in theory, the RHS operator
const int operator[](const int i ) const;
// in theory, the LHS operator
int& operator[](const int i );
//...
}

Here RHS stands for right-hand-side, or an r-value and LHS stands
for left-hand-side, or an l-value.

MyClass foo;

int i = foo[j]; // RHS reference NOT!
foo[j] = i; // LHS reference

Much to my surprise, the first statement "i = foo[j];" seems to
invoke the overloaded operator I've labeled LHS. I tried this with
Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
for Intel on freeBSD. Both compilers got the same results.

To put things in more concrete form, I've included a complete test
code below:

#include <stdio.h>

class overloaded
{
private:
int *pArray;

public:
overloaded( size_t size )
{
pArray = new int[ size ];
}

~overloaded()
{
delete [] pArray;
}

// in theory, the RHS operator
const int operator[](const int i ) const
{
printf("RHS a[%2d]\n", i );
return pArray;
}

// in theory, the LHS operator
int& operator[](const int i )
{
printf("LHS a[%2d]\n", i );
return pArray;
}
}; // overloaded


int
main()
{
const int len = 4;
overloaded a(len);
int b[len];

int i;

printf("initializing array...\n");
for (i = 0; i < len; i++) {
a = i + 1;
}

printf("reading values from array in an 'if' statement...\n");
for (i = 0; i < len; i++) {
if (a != i+1) {
printf("bad value");
break;
}
}

printf("reading values from an array in an assignment...\n");
for (i = 0; i < len; i++) {
b = a;
}

printf("expression...\n");
int j = a[1] + a[2];
return 0;
}

When I compile and execute this code I get

initializing array...
LHS a[ 0]
LHS a[ 1]
LHS a[ 2]
LHS a[ 3]
reading values from array in an 'if' statement...
LHS a[ 0]
LHS a[ 1]
LHS a[ 2]
LHS a[ 3]
reading values from an array in an assignment...
LHS a[ 0]
LHS a[ 1]
LHS a[ 2]
LHS a[ 3]
expression...
LHS a[ 1]
LHS a[ 2]

I expected that the "initialization" would reference the LHS form of
the overloaded function. However, much to my surprise, the 'if'
statement and the value reads also referenced the LHS form of the
overloaded operator. I'm surprised at this, since as far as I can
tell, this way I've implemented the overloaded [] operators is
pretty much "text book" approach.

Is there a way to implement this class so that the RHS [] will be
called when it seems to be an r-value? That is

if (a != i+1)
b = a;
int j = a[1] + a[2];

In this example the difference is not critical, since the code gets
the expected results. However, proper invokation of the RHS and LHS
operators is important in the case of reference counted objects,
which is the appliction that originally motivated this question.

I'm working on a third version of a reference counted String class,
which can be found here:
http://www.bearcave.com/software/string/index.html. This class
suffers from a bug caused by the behavior of the [] operator
described above. In particular, it is making too many copies.

I have noted Stroustrup's solution using the Cref class (from 11.12
of "The Book"). However, in his code it appears that you might as
well omit the RHS version of the [] operator.

I'd be grateful for a version of the test code above that invokes
the RHS operator for what appear to be r-value references. Could
you please copy any postings on this to "iank at bearcave dot com".
Thank you for your help,

Ian
iank at bearcave dot com
 
J

John Harrison

(null) said:
I have not posted to comp.lang.c++ (or comp.lang.c++.moderated)
before. In general when I have a C++ question I look for answers in
"The C++ Programming Language, Third Edition" by Stroustrup.
However, I've come upon a question that I can neither answer from
"The Book" or a Google search (so yes, at least I RTFBed). I'm
hoping that someone in this news group might know the answer.

Overloading the [] Operator

Say I want to develop a class that supports the overloaded []
operator and reads and writes the "int" type. I thought that the
way this was done was:

class MyClass
{
//...
// in theory, the RHS operator
const int operator[](const int i ) const;
// in theory, the LHS operator
int& operator[](const int i );
//...

I'd prefer

int operator[](int i ) const;
int& operator[](int i );

for an int type the other const's are unecessary.

Your comments about RHS operator and LHS operator are incorrect however. See
below.
}

Here RHS stands for right-hand-side, or an r-value and LHS stands
for left-hand-side, or an l-value.

MyClass foo;

int i = foo[j]; // RHS reference NOT!
foo[j] = i; // LHS reference

Much to my surprise, the first statement "i = foo[j];" seems to
invoke the overloaded operator I've labeled LHS. I tried this with
Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
for Intel on freeBSD. Both compilers got the same results.

[snip]


I expected that the "initialization" would reference the LHS form of
the overloaded function. However, much to my surprise, the 'if'
statement and the value reads also referenced the LHS form of the
overloaded operator. I'm surprised at this, since as far as I can
tell, this way I've implemented the overloaded [] operators is
pretty much "text book" approach.

Is there a way to implement this class so that the RHS [] will be
called when it seems to be an r-value? That is

if (a != i+1)
b = a;
int j = a[1] + a[2];


It would be nice if you could do what you want to do but you can't.

For clarity lets denote operator[] by F, and operator= by G, then
essentially what you are asking for is the compiler to distinguish between
calls to F in

G(...,F(i))

from

G(F(i), ...)

But the compiler cannot do this for any normal function so there is no
reason to expect it to work for operator[] and operator=.
In this example the difference is not critical, since the code gets
the expected results. However, proper invokation of the RHS and LHS
operators is important in the case of reference counted objects,
which is the appliction that originally motivated this question.

I'm working on a third version of a reference counted String class,
which can be found here:
http://www.bearcave.com/software/string/index.html. This class
suffers from a bug caused by the behavior of the [] operator
described above. In particular, it is making too many copies.

Right, which is why you should avoid operator[] on reference counted string
classes. It is impossible to implement in an efficient manner. Implementing
operator[] on a non-const reference counted string class means a compromise,
either you have to take a copy of the string immediately even though
operator[] might only be being used to read from the string, or you have to
write a proxy class (e.g. Cref in Stroustrup).
I have noted Stroustrup's solution using the Cref class (from 11.12
of "The Book"). However, in his code it appears that you might as
well omit the RHS version of the [] operator.

Well there is no RHS version of [] you have been misinformed. If you omitted
the const version of operator[] from Stroustrup's code then the following
would not compile

const String x = "abc";
cout << x[0];

This is the true meaning of the const version of operator[], it allows you
to access const objects. Same as any other const method.

john
 
J

John Harrison

I'm working on a third version of a reference counted String class,
which can be found here:
http://www.bearcave.com/software/string/index.html. This class
suffers from a bug caused by the behavior of the [] operator
described above. In particular, it is making too many copies.

BTW, from the above site

"When an STL string object is assigned to another string object, a copy is
made. In contrast, the String container copies a reference and increments a
reference count."

This is not strictly correct, the standard leaves it up to the
implementation whether to use reference counting or not. My version of the
STL (dinkumware) does use reference counting.

john
 
T

Thomas Mang

(null) said:
class MyClass
{
//...
// in theory, the RHS operator
const int operator[](const int i ) const;
// in theory, the LHS operator
int& operator[](const int i );
//...
}

All these members are in the private section of the class.
I assume you missed a "public:" somewhere.



Here RHS stands for right-hand-side, or an r-value and LHS stands
for left-hand-side, or an l-value.

MyClass foo;

int i = foo[j]; // RHS reference NOT!
foo[j] = i; // LHS reference

Much to my surprise, the first statement "i = foo[j];" seems to
invoke the overloaded operator I've labeled LHS.

No surprise at all.
Your foo-object is non-const, so the compiler invokes the non-const
overloaded operator[].
Why should it invoke the const version?

Things are totally different when foo is defined as const:

const MyClass foo;

Then the compiler will, of course, invoke the const-version of operator[].


Note that this overload resolution has nothing to do with the fact if you
use your overloaded operator[] at the call site as LHS or RHS.


regards,

Thomas
 
J

Joshua Lehrer

John Harrison said:
Right, which is why you should avoid operator[] on reference counted string
classes. It is impossible to implement in an efficient manner. Implementing
operator[] on a non-const reference counted string class means a compromise,
either you have to take a copy of the string immediately even though
operator[] might only be being used to read from the string, or you have to
write a proxy class (e.g. Cref in Stroustrup).


You seem to be making an assumption here. If I read your statement
correctly, you say that it is impossible to implement the non-const
index operator on a reference counted String in an efficient manner.
You then state that in order to do this, you need to write a proxy
class. Therefore, you are making the assumption that the proxy class
makes the class non-efficient.

This *may* not be true. It depends on if the compiler can optimize
away much, if not all, of the use of the proxy class.

Even if this one function makes the refernce counted String class
slightly less efficient to use, the other gains from the
refernce-counted String class *may* outweigh this small expense- it
proveably did on our system. The only way to tell on your system is
to try it.

We have a home grown reference counted String class, and it uses a
proxy class to implement the return value of the non-const index
operator. The class is extremely efficient, and fast. Our source
code base which uses this class has about 400 engineering-man-years of
development in it, consisting of hundreds of thousands of lines of
code. When we released our reference counted String class in place of
the old version, we saw at least a 10% improvement in our average CPU
consumption. Sections of our application which used Strings heavily
saw much more significant gains. We are certain that we would see
even more gains if we did not have legacy code that depended on
certain behaviors of the old String class, which required some slight
inefficiencies be purposely introduced into the new String class.

The bottom line- lots of reference-counted string bashing goes on in
this newsgroup. Most of this bashing is by people who probably never
wrote such a class themselves. We took the time to write one, and
thoroughly test and review it for completeness, correctness, and
safety. This class has had nothing but positive impact on *our*
system. Your mileage may vary.

joshua lehrer
factset research systems
NYSE:FDS

p.s. to order your very own "RefStrings Rule!" bumper-sticker, send a
self addressed stamped envelope to...
 
J

John Harrison

Joshua Lehrer said:
"John Harrison" <[email protected]> wrote in message
Right, which is why you should avoid operator[] on reference counted string
classes. It is impossible to implement in an efficient manner. Implementing
operator[] on a non-const reference counted string class means a compromise,
either you have to take a copy of the string immediately even though
operator[] might only be being used to read from the string, or you have to
write a proxy class (e.g. Cref in Stroustrup).


You seem to be making an assumption here. If I read your statement
correctly, you say that it is impossible to implement the non-const
index operator on a reference counted String in an efficient manner.
You then state that in order to do this, you need to write a proxy
class. Therefore, you are making the assumption that the proxy class
makes the class non-efficient.

OK, maybe I didn't choose the best words. Substitute 'as simply as you
think' for 'efficiently'.
This *may* not be true. It depends on if the compiler can optimize
away much, if not all, of the use of the proxy class.

Even if this one function makes the refernce counted String class
slightly less efficient to use, the other gains from the
refernce-counted String class *may* outweigh this small expense- it
proveably did on our system. The only way to tell on your system is
to try it.

Couldn't disagree with that.
We have a home grown reference counted String class, and it uses a
proxy class to implement the return value of the non-const index
operator. The class is extremely efficient, and fast. Our source
code base which uses this class has about 400 engineering-man-years of
development in it, consisting of hundreds of thousands of lines of
code. When we released our reference counted String class in place of
the old version, we saw at least a 10% improvement in our average CPU
consumption. Sections of our application which used Strings heavily
saw much more significant gains. We are certain that we would see
even more gains if we did not have legacy code that depended on
certain behaviors of the old String class, which required some slight
inefficiencies be purposely introduced into the new String class.

The bottom line- lots of reference-counted string bashing goes on in
this newsgroup.

Not by me (at least not intentionally). Hell, I even believe that copy on
write is a generally useful technique.
Most of this bashing is by people who probably never
wrote such a class themselves. We took the time to write one, and
thoroughly test and review it for completeness, correctness, and
safety. This class has had nothing but positive impact on *our*
system. Your mileage may vary.

joshua lehrer
factset research systems
NYSE:FDS

p.s. to order your very own "RefStrings Rule!" bumper-sticker, send a
self addressed stamped envelope to...

Where? Where can I get one!?

john
 
L

llewelly

I have not posted to comp.lang.c++ (or comp.lang.c++.moderated)
before. In general when I have a C++ question I look for answers in
"The C++ Programming Language, Third Edition" by Stroustrup.
However, I've come upon a question that I can neither answer from
"The Book" or a Google search (so yes, at least I RTFBed).

Well it is a big book sometimes people miss things, or don't add up
seperate things in the intended way. 10.2.6 explains constant
member functions.
I'm hoping that someone in this news group might know the answer.

Overloading the [] Operator

Say I want to develop a class that supports the overloaded []
operator and reads and writes the "int" type. I thought that the
way this was done was:

class MyClass
{
//...
// in theory, the RHS operator
const int operator[](const int i ) const;
// in theory, the LHS operator
int& operator[](const int i );

'const' is a propertery of an object, not of an operator=. If the
instance of MyClass is const, the first will be called, and if the
instance of MyClass is not const, the second will be called. This
is true regardless of which side of operator= the use of
operator[] occurs.

(Note: in order to have behavior more like that of builtin[], the
first operator[] should return 'int const&' )
//...
}

Here RHS stands for right-hand-side, or an r-value and LHS stands
for left-hand-side, or an l-value.

MyClass foo;

int i = foo[j]; // RHS reference NOT!
foo[j] = i; // LHS reference

Much to my surprise, the first statement "i = foo[j];" seems to
invoke the overloaded operator I've labeled LHS.
[snip]

This is correct behavior; foo is not const, so
int& MyClass::eek:perator[](int) is called, and not
int const MyClass::eek:perator[](int) const . It is constness,
and not side of operator=, that matters. Had you written:

MyClass const foo;

int i = foo[j];
foo[j]= i;

both calls would have called
int const MyClass::eek:perator[](int) const .
 
K

kanze

(e-mail address removed) (Joshua Lehrer) wrote in message

[...]
The bottom line- lots of reference-counted string bashing goes on in
this newsgroup. Most of this bashing is by people who probably never
wrote such a class themselves. We took the time to write one, and
thoroughly test and review it for completeness, correctness, and
safety. This class has had nothing but positive impact on *our*
system. Your mileage may vary.

I suspect that most of the bashing is an accidental extension of
reference-count bashing with regards to an implementation of
std::string. The standard does NOT allow the use of a proxy -- the
non-const version of operator[] must return a real reference. This
requires special handling even in a single threaded version with
reference counting, and is almost impossible to get right efficiently in
a multi-threaded version -- you end up needing a lock for practically
every single access.

For the rest, in the past, I too have found reference counting to be a
win. In my own code -- I can't speak for others. (Like you, my string
class used a proxy as the return value for the non-const operator[].)
 
C

Carl Barron

(null) said:
I have not posted to comp.lang.c++ (or comp.lang.c++.moderated)
before. In general when I have a C++ question I look for answers in
"The C++ Programming Language, Third Edition" by Stroustrup.
However, I've come upon a question that I can neither answer from
"The Book" or a Google search (so yes, at least I RTFBed). I'm
hoping that someone in this news group might know the answer.

Overloading the [] Operator

Say I want to develop a class that supports the overloaded []
operator and reads and writes the "int" type. I thought that the
way this was done was:

class MyClass
{
//...
// in theory, the RHS operator
const int operator[](const int i ) const;
// in theory, the LHS operator
int& operator[](const int i );
//...
}

Here RHS stands for right-hand-side, or an r-value and LHS stands
for left-hand-side, or an l-value.

MyClass foo;

int i = foo[j]; // RHS reference NOT!
foo[j] = i; // LHS reference

Much to my surprise, the first statement "i = foo[j];" seems to
invoke the overloaded operator I've labeled LHS. I tried this with
Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
for Intel on freeBSD. Both compilers got the same results.

To put things in more concrete form, I've included a complete test
code below:

#include <stdio.h>

class overloaded
{
private:
int *pArray;
const int rhs_bracket(i) const
{
// perform = overloaded_array
printf("RHS a[%2d]\n",i);
return pArray[i[;
}
void lhs_bracket(int i,int x)
{
// perform overloaded_array = x;
printf("LHS a[%2d] = %d\n",i,x);
pArray = x;
}
class proxy
{
overloaed *over;
int index;
proxy(overloaded *a,int b):eek:ver(a),index(b){}
public:
friend class overloaded;
operator int() { return over->rhs_bracket(i);}
proxy & operator = (int x)
{
over->lhs_bracket(i,x);
return *this;
}
};
friend class proxy;
proxy operator [] (int i) {return proxy(this,i);}
overloaded( size_t size )
{
pArray = new int[ size ];
}

~overloaded()
{
delete [] pArray;
}
#if 0
// in theory, the RHS operator
const int operator[](const int i ) const
{
printf("RHS a[%2d]\n", i );
return pArray;
}

// in theory, the LHS operator
int& operator[](const int i )
{
printf("LHS a[%2d]\n", i );
return pArray;
} #endif

}; // overloaded
...

This will result in different behavior depending on whether operator
[] is used to read or write data to/from an overloaded.

Note i used mutual friendship so only overloaded::eek:perator [] will
create an overloaded::proxy objwct. and private functions to do the
different items on the lhs and rhs of an equal sign. Making them private
and proxy a friend means that only proxy is going to access these
implimentation detail functions. This approach can also be used with
operator *() and operator ->() to preform different operations when
reading and writing.
 
T

Thomas Mang

James said:
Normally, this should not be a problem. There are exceptions,
however, when you need to do something different if the target is
actually modified. In such cases, you typically need to use some sort
of Proxy, e.g.:

class MyClass
{
public:
class Proxy
{
friend class MyClass ;
public:
operator int() const
{
return myOwner.get( myIndex ) ;
}
Proxy const& operator=( int other ) const
{
myOwner.put( myIndex, other ) ;
return *this ;
}
private:
Proxy( MyClass& owner, int index )
: myOwner( owner )
, myIndex( index )
{
}

MyClass& myOwner ;
int myIndex ;
} ;

void put( int index, int newValue ) ;
int get( int index ) const ;

Proxy operator[]( int index )
{
return Proxy( *this, index ) ;
}
int operator[]( int index ) const
{
return get( index ) ;
}
} ;

All of the actual logic is then in get and put.

What advantage does one gain by writing a proxy class, instead of simply
returning an int&?

That is, why not simply write the following overloaded operator[]?

int& operator[](int index)


regards,

Thomas
 
G

Glen Low

Much to my surprise, the first statement "i = foo[j];" seems to
invoke the overloaded operator I've labeled LHS. I tried this with
Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
for Intel on freeBSD. Both compilers got the same results.

What you need is to return a proxy class that overloads operator= and
operator int. Roughly:

class MyClass
{
public:
int operator[] (int i) const; // RHS
int_proxy operator[] (int i) { return int_proxy (p_ + i); }
private:
int *p_;
};

class int_proxy
{
public:
int_proxy& operator= (int val) { *r_ = val; }
operator int () const; // RHS
int_proxy (int* r): r_ (r) { }
private:
int *r_;
};

Essentially the int_proxy acts like a int&, but whatever special code
you would have put in the RHS function in the original, you put that
same code in the RHS function in the proxy. (Stylistically, you could
use templates and put int_proxy inside of MyClass.) I believe
std::vector<bool> is specialized to do this.

Now when you call a , you get a temporary proxy. If there is an
access, then operator int gets called with your special RHS code; if
there is a mutate, then operator= gets called.

If it's all inline and optimizations are on, chances are the compiler
will optimize away the temporary int_proxy object. The only drawback I
can see is that the return type is no longer int&, which may crap out
code that expects it e.g. int& ri = a .

P.S. If you're irritated by having to repeat RHS code twice, either
cause the int_proxy version to call the MyClass version, or return a
const int_proxy from the MyClass RHS function.
 
R

Rob

(null) said:
class MyClass
{
//...
// in theory, the RHS operator
const int operator[](const int i ) const;
// in theory, the LHS operator
int& operator[](const int i );
//...
}

Here RHS stands for right-hand-side, or an r-value and LHS stands
for left-hand-side, or an l-value.

MyClass foo;

int i = foo[j]; // RHS reference NOT!
foo[j] = i; // LHS reference

Much to my surprise, the first statement "i = foo[j];" seems to
invoke the overloaded operator I've labeled LHS. I tried this with
Microsoft's Visual C++ 6.0 compiler, I think upgraded with at least
service pack 5 (version 12.00.8804) and the GNU 2.95.2 g++ compiler
for Intel on freeBSD. Both compilers got the same results.
[Snip]

This is actually the way it's supposed to be. foo is not a const object,
so when
there is a choice (as in this case) the non-const version of the operator
should
be invoked.
 
S

Siemel Naran

Francis Glassborow said:
class hue{
public:
bool operator[](int bit)const {
if(bit <0 or bit >7) return false;
return bitset<8>(code_)[bit];
}
class ref;
friend class hue::ref;
class ref{
public:
ref(hue & h, int n):h_(h),bit(n){};
operator bool(){
if (bit <0 or bit >7) return false;
return bitset<8>(h_)[bit];
}
void operator=(bool val){
if(bit <0 or bit >7) return;
bitset<8> v(h_);
v[bit] = val;
h_ = (unsigned char)v.to_ulong();
}
private:
hue & h_;
int bit;
};
ref operator[](int bit){return ref(*this, bit);}

How do you deal with the problem of replicating the interface of class bool
in class hue::ref? No problem with class bool as you only have to worry
about operator= as you did above (and I did in my example). But what about
other member functions like operator+=, memfun(), etc?
 
G

Glen Low

That is, why not simply write the following overloaded operator[]?
int& operator[](int index)

An int& is dumb, it cannot distinguish whether it is being written to
or read. A proxy object is smart, it knows when it is written (via
operator=) or read (via operator int), and can execute different code
as a result.
 
F

Francis Glassborow

In message said:
How do you deal with the problem of replicating the interface of class bool
in class hue::ref? No problem with class bool as you only have to worry
about operator= as you did above (and I did in my example). But what about
other member functions like operator+=, memfun(), etc?

Sorry, I am totally confused. bool is a fundamental type and not a
class. Operator bool 'returns' a bool by value.
 
S

Siemel Naran

Francis Glassborow said:
Sorry, I am totally confused. bool is a fundamental type and not a
class. Operator bool 'returns' a bool by value.

Say you have a class Foo. The operator[] that is non-const returns a proxy.
There is a function operator const Foo&() const. Then there is a function
void operator=(const Foo&). What about other member functions of class Foo?
So that we can say

EnvelopeClass env;
env["abc"]; // returns EnvelopeClass::reference, which is conceptually a
Foo&
env["abc"] = Foo(3); // ok
env["abc"].memfun(); // oops

For the last line to work, class EnvelopeClass::reference should have a
member function memfun() because class Foo has such a function. Then we
have to duplicate the entire interface of class Foo inside Foo::reference.
Quite a nuisance.
 
F

Francis Glassborow

In message said:
Say you have a class Foo. The operator[] that is non-const returns a proxy.
There is a function operator const Foo&() const. Then there is a function
void operator=(const Foo&). What about other member functions of class Foo?
So that we can say

EnvelopeClass env;
env["abc"]; // returns EnvelopeClass::reference, which is conceptually a
Foo&
env["abc"] = Foo(3); // ok
env["abc"].memfun(); // oops

For the last line to work, class EnvelopeClass::reference should have a
member function memfun() because class Foo has such a function. Then we
have to duplicate the entire interface of class Foo inside Foo::reference.
Quite a nuisance.

No, you are making assumptions as to what the class designer should
expose. The point of using a proxy class is exactly that it give the
class designer control whilst the return of a reference abandons it. If
we write any function that returns a plain reference to private data we
have exposed that data and lost control of it. The main motive for
having private data is exactly to avoid such circumstances. If a member
function returns a plain reference we might as well make the data
public.
 
A

Andrey Tarasevich

Francis said:
...
No, you are making assumptions as to what the class designer should
expose. The point of using a proxy class is exactly that it give the
class designer control whilst the return of a reference abandons it.
If
we write any function that returns a plain reference to private data we
have exposed that data and lost control of it.

Not true. We gave user full control of the value, which doesn't
necessarily mean that we "lost" control of it in negative sense of the
word, since the object that returned the reference might not even care
about this control.
The main motive for
having private data is exactly to avoid such circumstances. If a member
function returns a plain reference we might as well make the data
public.
...

Not true.

There still is one (although thin) level of protection that is not
destroyed by returning a reference to private data. It doesn't expose
the actual location of the lvalue, i.e. it doesn't declare loud and
clear that the returned reference is bound to a subobject of the class.
Making a subobject 'public' immediately removes this last layer of
protection.

For example, making a subobject 'public' allows user to make assumptions
about the lifetime of subobject based on the lifetime of the entire
object. Accessor member function that returns a reference prevents user
to make such assumptions.
 
A

Andrey Tarasevich

Francis said:
...
No, you are making assumptions as to what the class designer should
expose. The point of using a proxy class is exactly that it give the
class designer control whilst the return of a reference abandons it.
If
we write any function that returns a plain reference to private data we
have exposed that data and lost control of it.

Not true. We gave user full control of the value, which doesn't
necessarily mean that we "lost" control of it in negative sense of the
word, since the object that returned the reference might not even care
about this control.
The main motive for
having private data is exactly to avoid such circumstances. If a member
function returns a plain reference we might as well make the data
public.
...

Not true.

There still is one (although thin) level of protection that is not
destroyed by returning a reference to private data. It doesn't expose
the actual location of the lvalue, i.e. it doesn't declare loud and
clear that the returned reference is bound to a subobject of the class.
Making a subobject 'public' immediately removes this last layer of
protection.

For example, making a subobject 'public' allows user to make assumptions
about the lifetime of subobject based on the lifetime of the entire
object. Accessor member function that returns a reference prevents user
to make such assumptions.
 
G

Glen Low

EnvelopeClass env;
env["abc"]; // returns EnvelopeClass::reference, which is conceptually a
Foo&
env["abc"] = Foo(3); // ok
env["abc"].memfun(); // oops

For the last line to work, class EnvelopeClass::reference should have a
member function memfun() because class Foo has such a function. Then we
have to duplicate the entire interface of class Foo inside Foo::reference.
Quite a nuisance.

At the cost of some minor ickiness you could:
1. Make the proxy overload operator*, operator-> and operator->*
(can't remember whether you can overload operator.*). So you could do
something like env["abc"]->memfun ();
2. For consistency, you could have operator= take a T*.
3. Entirely different track: both the proxy and the object could
inherit from some base class, using the "curiously recursive" pattern
to avoid virtual functions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,271
Latest member
BuyAtenaLabsCBD

Latest Threads

Top