⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 index.html

📁 《Big C++ 》Third Edition电子书和代码全集-Part1
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<!-- -*-*-HTML-*-*-
	$Source: /usr/local/cvsroot/BigC++/18/index.html,v $
	$Revision: 1.13 $
	Big C++, chptr 18
	editor: cols=80, tabstop=2

	(c) 2005 John Wiley & Sons
	Kurt Schmidt, kschmidt@cs.drexel.edu

	NOTES
	- 3 spaces are used for each indent in examples

	REVISION
		11/25/04 - creation
		12/4/03 - added js functions for title, image, and iframe, KS
						- made directory self contained (no references up), KS
		12/17/03 - moved title() into <head>, added summary, KS
		12/17/03 - numbered all headings, KS
		1/4/03 - removed sloppy commenting, made h1 same as others
		$Log: index.html,v $
		Revision 1.13  2004/04/26 04:56:49  kurt
		trimmed slides some more
		
		Revision 1.12  2004/04/26 04:55:04  kurt
		trimmed slides some more
		
		Revision 1.11  2004/04/12 05:00:39  kurt
		added copyright meta tags
		
		Revision 1.10  2004/03/29 05:49:14  kurt
		Pared language, fixed tabs (spaces), added copyright to comments
		
-->

<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
	<meta name='Copyright' content='2005 John Wiley & Sons'>
	<meta name='Author' content='Kurt Schmidt'>
	<script language="JavaScript" src="./config.js"></script>
	<script language="JavaScript" src="./pageFormat.js"></script>
	<script><!-- // Set title on browser window
		title()
	//--></script>
</head>

<body>

<h2><font color="#009999" size="+3">Chapter 18 - Memory
	Management</font></h2>
<font size="+1">

<script><!-- 
	image( "cover.png" )
//--></script>

</font>

<hr><h2><font color="#009999">Chapter Goals</font></h2>
<hr noshade size="4" color="#009999">
<font size="+1">

<ul>
	<li>To learn the different categories of memory</li>
	<li>To understand how to avoid common memory management errors</li>
	<li>To learn to write and use constructors and destructors</li>
	<li>To be able to create classes that manage their own memory
		allocation and deallocation</li>
</ul>

</font>

<hr><h2><font color="#009999">18.1 Categories of Memory</font></h2>
<font size="+1">

Memory is divided into four categories:

<ol>
	<li><i>Code</i> - instructions for all global and member functions</li>
	<li><i>Static Data</i> - global variables, and all local and member
		variables declared <tt>static</tt></li>
	<li><i>Run-time Stack</i> - automatics (local non-static)</li>
	<li><i>Free Store (Heap)</i> - dynamically allocated (<tt>new</tt>)</li>
</ol>

</font>

<hr><h2><font color="#009999">18.1.1 Code Memory</font></h2>
<font size="+1">

<ul>
	<li>Contains all machine instructions for functions and methods</li>
	<li>May be referenced through pointers
		<ul>
			<li>(See next chptr. and Lippman[1] for discussion on function
				pointers)</li>
		</ul>
	</li>
</ul>

</font>

<hr><h2><font color="#009999">18.1.2 Static Data Memory</font></h2>
<font size="+1">

<ul>
	<li>Globals, static locals and static member variables</li>
	<li>Size of statics can be known prior to execution</li>
	<li>Created <i>only once</i></li>
	<li>Initialized <i>only once</i>, before <tt>main</tt></li>
</ul>

</font>

<hr><h2><font color="#009999">18.1.3 The Run-time Stack</font></h2>
<font size="+1">

<ul>
	<li>Used for functions</li>
	<li>Every call is a new <i>activation record</i> on stack</li>
	<li>Activation record contains:
		<ul>
			<li>Parameters</li>
			<li>Return pointer</li>
			<li>Local variables</li>
			<li>Other machine-specific stuff</li>
		</ul>
	</li>
	<li>Return from function decrements stack pointer</li>
	<li>Drawbacks:
		<ul>
			<li>Local variables cease to exist when function exits</li>
			<li>Size of locals must be known at compile time</li>
		</ul>
	</li>
</ul>

</font>

<hr><h2><font color="#009999">18.1.4 The Run-time Stack (example)
	</font></h2>
<font size="+1">

<table>
	<tr>
		<td valign='top' width='50%'><font size='+1'> If function <i>f</i> has
			called <i>g</i>, which, in turn, called <i>h</i>, then the stack looks
			something like this:<br><br>
		</td>
		<td>
			<script><!-- 
				image( "fig1.png" )
			//--></script>
		</td>
	</tr>
</table>

<!--	This is a table I made in lieu of figure 1.  KS
<table border="5" width="80%" bgcolor="#C0C0C0">
  <tr>
    <td width="50%" align="center"><b>...</b></td>
    <td width="50%" align="center">
			&lt;- &nbsp;Top of stack</td>
  </tr>
  <tr>
    <td width="50%" align="center" bgcolor="#00CC00">
			Local variables for <i>h</i></td>
    <td width="50%" rowspan="3" align="center" bgcolor="#00CC00">
			Activation record<br> for <i>h</i></td>
  </tr>
  <tr>
    <td width="50%" align="center" bgcolor="#00CC00">
			Return address back to <i>g</i></td>
  </tr>
  <tr>
    <td width="50%" align="center" bgcolor="#00CC00">
			Parameters for <i>h</i></td>
  </tr>
  <tr>
    <td width="50%" align="center" bgcolor="#FFFF00">
			Local variables for <i>g</i></td>
    <td width="50%" rowspan="3" align="center" bgcolor="#FFFF00">
			Activation record<br> for <i>g</i></td>
  </tr>
  <tr>
    <td width="50%" align="center" bgcolor="#FFFF00">
			Return address back to <i>f</i></td>
  </tr>
  <tr>
    <td width="50%" align="center" bgcolor="#FFFF00">
			Parameters for <i>g</i></td>
  </tr>
  <tr>
    <td width="50%" align="center" bgcolor="#009999">
			Local variables for <i>f</i></td>
    <td width="50%" rowspan="3" align="center" bgcolor="#009999">
			Activation record<br> for <i>f</i></td>
  </tr>
  <tr>
    <td width="50%" align="center" bgcolor="#009999">
			Return address back to <i>f</i>'s caller</td>
  </tr>
  <tr>
    <td width="50%" align="center" bgcolor="#009999">


			Parameters for <i>f</i></td>
  </tr>
  <tr>
    <td width="50%" align="center"><b>...</b></td>
    <td width="50%" align="center">&nbsp;</td>
  </tr>
</table>
-->

</font>

<hr><h2><font color="#009999">Heap Memory</font></h2>
<font size="+1">

The <i>heap</i>, or <i>free store</i>:

<ul>
	<li>Request storage area with <tt>new</tt></li>
	<li>Values accessed through a pointer</li>
	<li>Neither the number of values, nor the size of a particular value
		need be known at compile time</li>
	<li>Lifetime of a value is not tied to a function</li>
	<li>Values may persist after program ends</li>
	<li>Space returned to heap using <tt>delete</tt></li>
</ul>

</font>

<hr><h2><font color="#009999">18.2 Common Memory Errors</font></h2>
<font size="+1">

<ul>
	<li>The programmer is responsible for memory management in C++</li>
	<li>Pointers can refer to memory in any of the four areas (above)</li>
	<li>Possible errors include:
		<ul>
			<li>Using a value that has not been initialized</li>
			<li>Using a pointer to reference a memory location that is no longer
				valid (dangling pointer)</li>
			<li>Forgetting to delete a dynamically allocated section of memory
				(memory leak)</li>
			<li>Deleting a memory value that was never allocated</li>
			<li>Deleting a dynamically allocated section of memory more than
				once</li>
		</ul>
	</li>
</ul>

</font>

<hr><h2><font color="#009999">18.3 Constructors</font></h2>
<font size="+1">

<p>(introduced in Chptr. 6)</p>

<ul>
	<li>Same name as the class</li>
	<li>No return type</li>
	<li>Used to initialize class' attributes</li>
	<li>May be overloaded</li>
	<li>Only one c'tor is invoked at creation</li>
	<li>Implicitly invoked:</li>
		<ul>
			<li>Each time a block is entered where an object is declared</li>
			<li>For static objects - before <tt>main</tt> starts</li>
			<li>When an object is created on the heap with <tt>new</tt></li>
			<li>When an object is passed <i>by value</i></li>
			<li>For member objects, when aggregate is created</li>
			<li>When child is instantiated</li>
		</ul>
	</li>
</ul>

</font>

<hr><h2><font color="#009999">18.3 (cont.) Constructors - String
	Example</font></h2>
<font size="+1">

<p>E.g., <tt>String</tt> class, with underlying array on heap.</p>

<blockquote>
<pre>class String
{
public:
   String(); <font color="#0000cc">// Default constructor</font>
   String(const char p[]); <font color="#0000cc">// Simple constructor</font>
   String(const String&amp; right); <font color="#0000cc">// Copy constructor</font>
   ~String(); <font color="#0000cc">// Destructor</font>
   String&amp; operator=(const String&amp; right); <font color="#0000cc">// Assignment operator</font>
   String&amp; operator+=(const String&amp; right);
   int length() const;
   char&amp; operator[](int index);
   char operator[](int index) const;
private:
   char* buffer;
   int len;
};</pre>
</blockquote>

</font>

<hr><h2><font color="#009999">18.3.1 Constructors with Arguments</font></h2>
<font size="+1">

<ul>
	<li>All constructors perform necessary initialization</li>
	<li>Example:  Our c'tor must allocate space from heap and initialize:

	<blockquote>
<pre>String::String(const char p[])
{
   <font color="#0000cc">// Determine number of characters in string (strlen(p))</font>
   len = 0;
   while (p[len] != '\0')
      len++;
   <font color="#0000cc">// Allocate buffer array, remember to make space for NULL character</font>
   buffer = new char[len + 1];
   <font color="#0000cc">// Copy new characters (strcpy( buffer, p ))</font>
   for (int i = 0; i &lt; len; i++)
      buffer[i] = p[i];
   buffer[len] ='\0';
}</pre>

	<p>(Operators as described in chptr. 17)</p>
	</blockquote>

	</li>
</ul>

</font>

<hr><h2><font color="#009999">18.3.2 Default Constructors</font></h2>
<font size="+1">

<ul>
	<li>The constructor that takes no arguments</li>
	<li>Invoked <i>without</i> parenthesis, (except for unnamed temporaries</li>
	<li>Invoked:
		<ul>
			<li>When a variable is declared (or created from the heap) with no
				arguments</li>
			<li>The <i>only</i> initializer for elements in an array</li>
			<li>When object is member data of another class, and no initializer
				is provided</li>
		</ul>
	</li>
</ul>

</font>

<hr><h2><font color="#009999">18.3.2 Default Constructors (cont.)</font></h2>
<font size="+1">

<ul>
	<li>Example: a <tt>String</tt> is, by default, an empty string

	<blockquote>
<pre>String::String()
{
   len = 0;
   buffer = NULL; <font color="#0000cc">// No need to allocate array to hold zero characters</font>
}</pre>
	</blockquote>

	</li>
</ul>

</font>

<hr><h2><font color="#009999">18.3.3 Copy Constructors</font></h2>
<font size="+1">

<ul>
	<li>Sole parameter is a const reference to an object of the
		same class</li>
	<li><i>Automatically supplied by compiler</i> - memberwise (shallow)
		copy by default</li>
	<li>Calls copy c'tor of all member data</li>
	<li>Used to copy (clone) a value</li>
</ul>

</font>

<hr><h2><font color="#009999">18.3.3 Copy Constructors (cont.)</font></h2>
<font size="+1">

<ul>
	<li>Example:  each <tt>String</tt> has its own dynamically allocated
		buffer, so default behavior is insufficient.  We extend this behavior:

		<blockquote>
<pre>String::String(const String&amp; right)
{
   int n = right.length();
   buffer = new char[n + 1];
   for (int i = 0; i &lt; n; i++)
      buffer[i] = right[i];
   buffer[n] = '\0';
}</pre>
		</blockquote>

	</li>
</ul>

</font>

<hr><h2><font color="#009999">18.3.3 Copy Constructors (cont.)</font></h2>
<font size="+1">

Invoked:
<ul>
	<li>Explicitly
		<blockquote>
			String first("Fred");<br>
			String second(first);
			<font color="#0000cc">// second is initialized from first using copy
				constructor</font></tt>
		</blockquote>
	</li>
	<li>During initialization using <tt>=</tt></li>
		<blockquote>
			String third = first;
			<font color="#0000cc">// Also uses copy constructor</font></tt>
		</blockquote>
	</li>
	<li>When an object is passed <i>by value</i></li>
		<ul>
			<li><font color="#009999"><b>Note:</b></font> Use <tt>const</tt> when
				passing a reference to avoid copy overhead</li>
		</ul>
</ul>

</font>

<hr><h2><font color="#009999">18.3.4 Field Initializer Lists</font></h2>
<font size="+1">

Member data may be assigned in a field initializer list.

<ul>
	<li>Syntax only valid for constructors</li>
	<li>Used to avoid modifying an attribute twice (default c'tor,
	then in the body of the outer c'tor):</li>
</ul>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -