0

This may sound silly.

I have a class that contains a vector of pointers to instantiated objects.
I want to return a refrence to that vector, but I don't want to be able to modify the vector through that refrence.
Now, if i return a const reference, the vector is const, but the objects pointed by within the vector can still be modified via the pointer.

As a short example:

lass VecC
{
	vector<int*> myV;
public:
	VecC( int xx)
	{
		int *wtf = new int(xx);
		myV.push_back(wtf);
		
	};

	const vector<int*> & getV() { return myV; };
};

int main( int argc, char* argv[] )
{
	VecC obj(5);

	const vector<int*> & ref = obj.getV();

	*ref.at(0) = 9; // I WANT THIS TO NOT BE ALLOWED
}

Is this possible?
Thx in advance

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by dougy83
0

If you want the ints to be read only, make them const also (requires the following casting):

const vector<const int*> &  getV() { return *(const vector<const int*>*)&myV; };
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.