new
and delete
const unsigned mu_population = 24000; static personel_record[mu_population];
char line[100]; while (cin >> line) { ... }
cin.getline(line, 100)
.
const unsigned ln_size = 100
.
struct C { data * data_ptr; C() : data_ptr(new data) { } }; static void t(void) { C c; }
struct C { data * data_ptr; C() : data_ptr(new data) { } ~C() { delete data_ptr; } }; static void t(void) { C c; }
NULL
- a question of style
struct C { data * data_ptr; C() : data_ptr(new data) { } ~C() { delete data_ptr; } }; static void t(C & c) { C local_c(c); }
t()
, local_c.data_ptr
is c.data_ptr
.
*(local_c.data_ptr)
change *(c.data_ptr)
.
*(local_c.data_ptr)
deletes *(c.data_ptr)
.
void t(C c) { }
The call t(c)
makes a copy of c
.
C::C(const C &)
.
&
.
struct C { data * data_ptr; C() : data_ptr(new data) { } C(const C & c) : data_ptr(data_clone(c.data_ptr)) {} ~C() { delete data_ptr; } }; static void t(C & c) { C local_c(c); }
struct C { data * data_ptr; C() : data_ptr(new data) { } C(const C & c) : data_ptr(data_clone(c.data_ptr)) {} ~C() { delete data_ptr; } }; static void t(C & c) { C local_c; local_c = c; }
The contents of c.data_ptr
replaces the contents of
local_c.data_ptr
.
local_c.data_ptr
is garbage.
local_c.data_ptr
and c.data_ptr
are sharing memory.
=
.
=
.
struct C { data * data_ptr; C() : data_ptr(new data) { } C(const C & c) : data_ptr(data_clone(c.data_ptr)) {} ~C() { delete data_ptr; } C & operator = (const C & c) { // Bad example. delete data_ptr; data_ptr = data_clone(c.data_ptr); return *this; } }; static void t(C & c) { C local_c; local_c = c; }
a = a
self-assignment does occur in code.
a = a
?
struct C { data * data_ptr; C & operator = (const C & rhs) { delete data_ptr; data_ptr = copy_data(rhs.data_ptr); return *this; } };
Deallocating in lhs also deallocates in rhs.
a = a
, *this = rhs
.
data_ptr
deletes rhs.data_ptr
.
*this
is different from rhs
.
*this
and rhs
are different, proceeds as normal.
*this
and rhs
are the same, be careful.
struct C { data * data_ptr; C & operator = (const C & rhs) { if (this != &rhs) { delete data_ptr; data_ptr = copy_data(rhs.data_ptr); } return *this; } };
x = y = z = 0.0;
T & operator = (const T & rhs)
.
*this
.
T operator = (const T & rhs)
is more expensive - makes a copy.
turtle t1 = t2;
This page last modified on 4 April 2002.