Re: learner's question on populating vector< pair<int, string>* > as
member
On Apr 29, 1:38 pm, Triple-DES <DenPlettf...@gmail.com> wrote:
On 29 Apr, 11:31, James Kanze <james.ka...@gmail.com> wrote:
On Apr 29, 7:41 am, Triple-DES <DenPlettf...@gmail.com> wrote:
On 28 Apr, 10:10, James Kanze <james.ka...@gmail.com> wrote:
subramanian10...@yahoo.com, India wrote:
Test::~Test()
{
for (container_type::iterator it = c.begin(); it != c.=
end(); +
+it)
{
delete *it;
*it = 0;
Formally (but only formally), this is undefined behavior. You
must set the pointer in the container to null before the delete.
Why is that?
Because all objects in a container must be copiable, and a
deleted pointer is not copiable. In practice, of course
[snip]
You are right. 3.7.3.2/4 does indeed say that "The effect of using an
invalid pointer value (...) is undefined". But doesn't this also mean
that formally, setting the pointer to null is also undefined, because
"An object (...) is _used_ if its name appears in a potentially-
evaluated expression" (3.2/2)?
int * p = new int(5);
delete p;
p = 0; // undefined
p = new int(42); // reusing the ptr, fairly common, but undefined
char buf[sizeof(p)]; // ok, p is not _used_
Or am I missing something?
The fact that using an object doesn't necessarily mean using its
value? In general, I'd say that you only use its value if there
is either an lvalue to rvalue conversion, or an operation that
is described in terms of other operations which would involve an
lvalue to rvalue conversion. (That latter sounds a bit
complicated, but all it's saying is that ++p would use the
value, because it is defined as the equivalent of p = p + 1, and
the second use of p there involves an lvalue to rvalue
conversion.)
Historically, this rule dates back from the time when machines
had separate address registers, and loading an invalid address
into an address register could trap. Except that it's not
really that historical, since at least one machine still being
sold today today supports 48 bit pointers, and if the upper 16
bits aren't valid, loading the address could trigger a hardware
exception of some sort. So if the implementation of delete
returns the memory to the OS, and the OS unmaps it, just copying
the pointer, or reading it in any other way, could trap.
--
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