constness of vector of pointers
| maloner (1) | |||
| 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 | |||
| cpjust (9) | |||
| 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:
| |||
| ropez (312) | |||
This is equivalent, and might be more efficient:
| |||
This topic is archived - New replies not allowed.
