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 Alf P. Ste » Tue, 03 Mar 2009 15:52:30


* XXXX@XXXXX.COM :

That would allow you to change a constant object, like e.g.

char const* const s = "puck";

std::list<char*> varList;
std::list<char const*>& constList = varList; // !Not allowed

constList.push_back( s );
char* const p = *varList.begin();
p[0] = 'f';



You're providing too little information to give any definite answer -- see the
FAQ about How To Post.

However, it does *seem* as if you're missing three important concepts and have
one misconception, none of them directly related to the 'const' issue:

* Probably missing, the concept of referring to something (via a pointer or
C++ reference doesn't matter in that respect). Reasons that it's probably
missing: having a list of raw pointers, returning a result by reference.

* Probably missing, the concept of object lifetime. Reason it's probably
missing: returning by reference.

* Probably missing, the concept of Return Value Optimization (RVO). Reason
it's probably missing: returning by reference.

* Probable misconception, that micro efficiency matters a lot. Reason it's
probably there: returning by reference, using a list of raw pointers.

If so the only cure is experience coupled with correct information (e.g. a good
book, or for that matter Usenet discussions).

But one doesn't always need to know the details of what's wrong in order to
suggest a cure.

In the only example you've given I suggest using std::list< std::string >, and
return that type directly (not tacking on a '&' at the end).


Cheers & hth.,

- Alf

--
Due to hosting requirements I need visits to [ http://www.yqcomputer.com/ ].
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!