const reference

D

desktop

I have the following:

template <typename T, unsigned int N>
class MyVector {
protected:
std::vector<T> mVec;
public:
MyVector() : mVec(N,T()){}


// (1)
T& operator[] (unsigned int i) {
std::cout << "blop1\n";
return mVec;
}

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

When I do something like:

MyVector<int,3> bob;
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).
 
V

Victor Bazarov

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

When I do something like:

MyVector<int,3> bob;
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, 3> to 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
 
D

Daniel Kraft

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

When I do something like:

MyVector<int,3> bob;
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, 3> to 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
 

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,276
Latest member
Sawatmakal

Latest Threads

Top