Re: Constness with standard containters of pointers
Victor Bazarov a =E9crit :
James Kanze wrote:
On 16 mai, 19:29, Victor Bazarov <v.Abaza...@comAcast.net> wrote:
Javier wrote:
[..] if I have:
class A
{
public:
...
std::list< B * > & getList() { return m_list; };
const std::list< const B * > & getList() const
{ ...???... };
private:
std::list< B * > m_list;
}
What should I write in the const version of "getList()"?
You can't do much there. list<T> and list<const T> are
different types and cannot be converted into each other.
That's not quite true. There's nothing to stop you from writing
something like:
std::list< B const* > const A::getList() const
{
return std::list< B const* >( m_list.begin(), m_list.end() ) ;
}
The OP had the function returning a _reference_.
A const reference. But that's not the point. You can easily
convert a list< T > to a list< T const >. You can also bind the
results of the conversion to a const reference (although in this
case, all that it will give you is a dangling reference). So
the probably solution in his case is to redeclare the function
to return an object, and use the conversion.
What about the conversion from "std::list< B * >" to "const
std::list< const B * >"... The second const changes the
template argument so, is it a different type?
Yep.
But the STL is designed so that you can convert any type of
sequence to any other type, as long as the contained
elements are convertible. I use this rather regularly for
initializations, but it works generally.
I believe we use the term "convert" overloadedly here. Just
as much as one can "convert" an int into a C string...
Yes and no. There's a very real sense that the above is a
conversion, unlike the that of an int into a string. Like most
C++ conversions, however, the result is an rvalue---a copy of
the initial object, and not the object itself.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34