std::list with const and non-const pointers - why aren't they type compatible?

std::list with const and non-const pointers - why aren't they type compatible?

Post by arijit7 » Tue, 03 Mar 2009 15:33:01


Hi

I was just wondering if the return type of a function is
"std::list<const char *> &", then what could be the harm if I return
"std::list<char *>"?

All I am saying there is, I have a list of 'non-const' pointers,
please treat that as 'const' pointer and don't try to mess with the
content pointed.

To me, it makes complete sense and valid thinking. Not sure what am i
missing??

Any help??

Thanks
Arijit
 
 
 

std::list with const and non-const pointers - why aren't they type compatible?

Post by arijit7 » Tue, 03 Mar 2009 16:31:30

Thanks Alf.

To answer few of your concerns, let me take an example.

class X {

const std::list<const MyDS *> & getMyDSLst() const {
return _M_MyDS_list; // Err, I can't because my data member list
(see below) is not a list of const pointers. Here, I wanted to return
a const reference to this class's data member '_M_MyDS_list' *without*
any casting. So, I was wondering why I can't, and you clarified well,
thanks!
}

// Why not define the data member (below) as "std::list<const MyDS
*>"? Becasue I don't want to use casts for the mutating member
function 'alterMyDSListElementsforSomeReason()' below. So, I wanted to
retain my representation as mutable internally and provide the world
with a const list to const pointers in the 'get...' function above.

void alterMyDSListElementsforSomeReason();

// Why am I storing raw pointers? Because, MyDS is a base class from
which MyExtenededDS1, MyExtenededDS2, MyExtenededDS3, etc would be
extended. And my list '_M_MyDS_list' would actually store pointers to
those extended class objects, to maintain relative sequence among
those and polymorphism info.

private:
std::list<MyDS *> _M_MyDS_list;
};

 
 
 

std::list with const and non-const pointers - why aren't they type compatible?

Post by arijit7 » Tue, 03 Mar 2009 16:37:23

Basically, I am wondering, what is the recommended way to address all
these issues.
 
 
 

std::list with const and non-const pointers - why aren't they type compatible?

Post by DerToppe » Tue, 03 Mar 2009 16:57:59


That's fine, although the standard probably says that you'll get
undefined behaviour. I used a lot of code like the following:#

std::vector<DerivedClass*> SomeVector;

const std::vector<BaseClass*> ReturnSomething ()
{
return reinterpret_cast<BaseClass*> (SomeVector);
}

This works perfectly, since you only return a const vector of objects,
so you cannot break the vector by adding pointers of the wrong type.
Unfortunately, this kind of downcast is considered potentially harmful
by the compiler, since the involved (template) types
vector<BaseClass*> and vector<Derived*> seem totally unrelated to the
compiler. I don't know whether there is a simply solution to this
problem (or rather a nuisance).

Regards,
Stuart