constness of vector of pointers

Hello,

I have some doubt regarding my code below

class A
{
public:
......
const vector<B *> *getB() const {return bval;}

private:
vector<B *> *bval;
};

I realize that the code does not preserve real constness since the caller of getB() con still manipulate the content pointed to by B *. So I decided to change it to


class A
{
public:
......
const vector<const B *> *getB() const;

private:
vector<B *> *bval;
};

Now the problem is that I cannot simply return bval directly due to a type mismatch. I can possibly do a reinterpret_cast, but that seems ugly. Or I can new a vector<const B *> * and copy the content of bval to the new vector *. That seems even uglier since the caller needs to delete the new const vector<B *> *. That prompt me to think of changing bval from a pointer to an object and having getB return an object. But that is obviously less efficient.

The constness issue seems painful. Can someone suggest a solution to my dilemma? That is, a way commonly used by professional programmers.

Thanks in advance.

maloner
You could create a new container of pointers and return that.
BTW, why is your vector itself a pointer? Just create a regular vector and return it by reference:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <vector>

using namespace std;

struct B
{
	int i;
};

class A
{
public:
	const vector<const B*> getB() const
	{
		const vector<const B*> ret( m_B.begin(), m_B.end() );
		return ret;
	}

private:
	vector<B*> m_B;
};

int main()
{
	A a;
	const vector<const B*> bVec = a.getB();

	return 0;
}
This is equivalent, and might be more efficient:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <vector>

using namespace std;

struct B
{
	int i;
};

class A
{
public:
	const vector<const B*> getB() const
	{
		return vector<const B*>( m_B.begin(), m_B.end() );
	}

private:
	vector<B*> m_B;
};

int main()
{
	A a;
	const vector<const B*> bVec = a.getB();

	return 0;
}

Topic archived. No new replies allowed.