By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,116 Members | 1,319 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,116 IT Pros & Developers. It's quick & easy.

const reference

P: n/a
I have the following:

template <typename T, unsigned int N>
class MyVector {
protected:
std::vector<TmVec;
public:
MyVector() : mVec(N,T()){}
// (1)
T& operator[] (unsigned int i) {
std::cout << "blop1\n";
return mVec[i];
}

// (2)
T const& operator[] (unsigned int i) const {
std::cout << "blop2\n";
return mVec[i];
}
....
....

When I do something like:

MyVector<int,3bob;
bob[2] = 77;
int a = bob[2];

only "blop1" gets printed.

What are the difference between returning a reference to T and a
reference to a const T? It seems that there is no reason to keep (2).
Aug 15 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
// (2)
T const& operator[] (unsigned int i) const {
std::cout << "blop2\n";
return mVec[i];
}
...
...

When I do something like:

MyVector<int,3bob;
bob[2] = 77;
int a = bob[2];

only "blop1" gets printed.

What are the difference between returning a reference to T and a
reference to a const T? It seems that there is no reason to keep (2).
If you change MyVector<int, 3to const MyVector<int, 3>, operator (2)
will be invoked; if you remove (2), you can not even read elements on a
vector declared const.

Yours,
Daniel

--
Got two Dear-Daniel-Instant Messages
by MSN, associate ICQ with stress--so
please use good, old E-MAIL!
Aug 15 '07 #2

P: n/a
Daniel Kraft wrote:
>// (2)
T const& operator[] (unsigned int i) const {
std::cout << "blop2\n";
return mVec[i];
}
...
...

When I do something like:

MyVector<int,3bob;
bob[2] = 77;
int a = bob[2];

only "blop1" gets printed.

What are the difference between returning a reference to T and a
reference to a const T? It seems that there is no reason to keep (2).

If you change MyVector<int, 3to const MyVector<int, 3>, operator (2)
will be invoked;
Most likely it's not going to compile: assigning to 'bob[2]' will not
be possible using a reference to const the operator[] retunrs.
>[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 15 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.