pointers to elements in containers
- From: "Paul" <vhr@xxxxxxxxxxxxxxxxx>
- Date: Mon, 4 Sep 2006 19:13:25 +0100
I have a class that looks like that:
struct Detail {
std::list<const std::string> fields;
std::list<const std::string*> key_fields;
};
The 'key_fields' container is meant to store pointers to the std:string's in
'fields', so Detail's constructor looks like the following:
Detail::Detail()
{
fields.push_back(std::string("string 1"));
key_fields.push_back(&fields.back());
fields.push_back(std::string("string 2"));
key_fields.push_back(&fields.back());
//...
}
This does not work: pointers to elements in 'fields' point to valid
locations only until the end of the constructor after which they change (if
addresses of elements stored in 'fields' were to be taken once the
constructor has completed). (I have tried variations on the same theme but
whatever the container - list or vector - and whatever the method of
obtaining the address the underlying principle seems to remain the same:
addresses of elements in a container storing objects change once the
constructor has completed.)
Working on the above, I assumed the following:
1) Addresses of the elements in a vector may change after resize(),
push_back(), insert(), erase() - perhaps a few others of the similar
nature - but if you take care and call resize() or reserve() beforehand and
then assign (through []), they should not. (Initially I tried it with a
vector, although later realised having a vector was not the issue.)
2) Lists (and maps) are not affected by (1), as far as elements other than
those immediately affected by the operation are concerned.
Could it be that real copies are created upon the exit from the constructor?
How is this generally defined?
(The reason why I have two containers above is because not all of the fields
required are actually keys - supposed to be unique and to contain data - so
I thought I would store keys separately for ease of manipulation.)
Thank you.
.
- Follow-Ups:
- Re: pointers to elements in containers
- From: Carl Daniel [VC++ MVP]
- Re: pointers to elements in containers
- Prev by Date: Re: c++ winform
- Next by Date: Re: pointers to elements in containers
- Previous by thread: I find a BIG bug of VS 2005 about string class!
- Next by thread: Re: pointers to elements in containers
- Index(es):
Relevant Pages
|