new
and delete
.
const unsigned mu_population = 24000 static personnel_record[mu_population]
char line[100] while (cin >> line) { ... }
cin.getline(line, 100)
.
const unsigned ln_size = 100
.
const unsigned line_size = 100 char line[line_size] while cin.getline(line, line_size) { ... }
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; } };
struct C { data * data_ptr; C() : data_ptr(new data) { } ~C() { delete data_ptr; } }; static void t(C & c) { C local_c(c); }
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() { delete data_ptr; } C(const C & c) : data_ptr(new data(*(c.data_ptr))) {...} };
struct C data * data_ptr; C() : data_ptr(new data) { } ~C() { delete data_ptr; } C(const C & c) : data_ptr(new data(*(c.data_ptr))) {...} static void t(C & c) {C local_c; local_c = c;}
local_c.data_ptr
is garbage.
local_c.data_ptr
and c.data_ptr
are sharing storage.
=
.
=
.
struct C data * data_ptr; C() : data_ptr(new data) {...} C(const C & c) : data_ptr(new data(*c.data_ptr)) {...} ~C() { delete data_ptr; } // Bad example. C & operator = (const C & c) { delete data_ptr; data_ptr = new data(*c.data_ptr); return *this; }
c = c
is a self-assignment.
c = c
?
C & C::operator = (const C & rhs) { delete data_ptr; data_ptr = copy_data(rhs.data_ptr); return *this; }
c = c
, *this = rhs
.
data_ptr
deletes rhs.data_ptr
.
*this
is different from rhs
.
*this
and rhs
are different,
proceed as normal.
*this
and rhs
are the same, do nothing.
C & C::operator = (const C & rhs) { if (this != &rhs) { delete data_ptr; data_ptr = new data(*(rhs.data_ptr)); } return *this; }
x = y = z = 0.0;
if ((ch = getch()) != EOF)
...
T & operator = (const T & rhs)
*this
.
C c2 = c1;
and
c2 = c1;
Or maybe there's no difference?
copying constructing defines an undefined instance.
C c2(c1);
class blob { public: ~blob() { delete(); } blob(const blob & b) { copy(b); } blob & operator = (const & blob b) { if (&b != this) { delete(); copy(b); } } private: void copy(const & blob b) {...} void delete() {...} };
If a class implements a destructor, a copy constructor, or an assignment operator, then it needs to implement all three.
A class with pointer instance variables must have a destructor, a copy constructor, and an assignment operator.