In this lab, we’ll show how you can redefine the new/delete operators to achieve a variety of useful or bizarre results.                 
The files for this lab are available in ~cs253/Labs/New.                 
Consider glob.cc. It redefines the global new
and delete
operators to add trace output. This could be useful in
figuring out just when new
and delete
are being invoked.
                
Note the function signatures—at this level, new
takes a size_t
and returns a void *
, whereas delete
takes a void *
and
returns void
.
                
Why does new
return void *
?
                
new
/delete
                Consider class.cc. It redefines the
class-specific new
and delete
operators to add trace output.
This will not affect new
and delete
operations on other types,
such as int
or double
.
main
, which function is called and why?
operator new
and operator delete
declared static
?
new
/delete
for a specific class                Try to compile forbid1.cc. Does it compile? Why not?                 
Try to compile forbid2.cc. Does it compile? Why not?                 
forbid-mixin.cc does the same thing as forbid1.cc & forbid2.cc, but encapsulates it in a “mixin”.                 
For another popular example of a mixin, see the Boost class noncopyable                 
Compile and execute errchk.cc. Observe the error message, and decide what caused it. How would you improve it to detect multiple deletions of the same memory? (You don’t need to write the code, just explain it.)                 
If you’re concerned about the contents of deleted memory getting reused, then consider the technique used in scrub.cc. What criteria would you use to decide on a value for memory? It should be:
For example, a repeated string of “Jack” or “WTF!” would fit all of the above requirements. Notably, an odd value makes for a poor pointer, and would often cause a segmentation violation upon use.                 
Run normal.cc.
class Foo
?
p
and q
? Why?
Now, run pool.cc.
class Bar
?
r
and s
? Why?
Of course, it’s a pain to have to redefine new
and delete
for every class. After we study templates, you will be able to
create a templated mixin to do the same for all classes.
                
new
and delete
for class Foo
,
and then derive class Bar
from class Foo
?
Bar
inherit the redefined new
and delete
?
sizeof(Bar) > sizeof(Foo)
?
NoNewDelete
in
forbid-mixin.cc does—it makes its subclass
require the use of new
.
Modified: 2017-03-07T12:10                  User: Guest                  Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |