C++ new/delete CSE 333 Spring 2018

C++ new/delete CSE 333 Spring 2018

L12: C++ Class Details, Heap C++ Class Details, Heap CSE 333 Spring 2019 Instructor: Justin Hsia Teaching Assistants: Aaron Johnston Andrew Hu Daniel Snitkovskiy Forrest Timour Kevin Bi Kory Watson Pat Kosakanchit Renshu Gu Tarkan Al-Kazily Travis McGaha CSE333, Spring 2019 L12: C++ Class Details, Heap CSE333, Spring 2019 Administrivia Exercise 10 released today, due Monday Write a substantive class in C++! Refer to Complex.h/Complex.cc Homework 2 due next Thursday (5/2) File system crawler, indexer, and search engine

2 L12: C++ Class Details, Heap CSE333, Spring 2019 Lecture Outline Class Details Filling in some gaps from last time Using the Heap new / delete / delete[] 3 L12: C++ Class Details, Heap CSE333, Spring 2019 Rule of Three If you define any of: 1) Destructor 2) Copy Constructor

3) Assignment (operator=) Then you should normally define all three Can explicitly ask for default synthesized versions (C++11): class Point { public: Point() = default; ~Point() = default; Point(const Point& copyme) = default; Point& operator=(const Point& rhs) = default; ... // // // // the the the the default default default default

ctor dtor cctor "=" 4 L12: C++ Class Details, Heap CSE333, Spring 2019 Dealing with the Insanity C++ style guide tip: If possible, disable the copy constructor and assignment operator by declaring as private and not defining them (pre-C++11) Point.h class Point { public: Point(const int x, const int y) : x_(x), y_(y) { } // ctor ... private: Point(const Point& copyme); // disable cctor (no def.) Point& operator=(const Point& rhs); // disable "=" (no def.)

... }; // class Point Point w; Point x(1, 2); Point y = w; y = x; // // // // compiler error (no default constructor) OK! compiler error (no copy constructor) compiler error (no assignment operator) 5 L12: C++ Class Details, Heap CSE333, Spring 2019 Disabling in C++11 C++11 add new syntax to do this directly This is the better choice in C++11 code Point_2011.h

class Point { public: Point(const int x, const int y) : x_(x), y_(y) { } // ctor ... Point(const Point& copyme) = delete; // declare cctor and "=" as Point& operator=(const Point& rhs) = delete; // as deleted (C++11) private: ... }; // class Point Point w; Point x(1, 2); Point y = w; y = x; // // // // compiler error (no default constructor) OK! compiler error (no copy constructor) compiler error (no assignment operator) 6 L12: C++ Class Details, Heap CSE333, Spring 2019

CopyFrom C++11 style guide tip: If you disable them, then you instead may want an explicit CopyFrom function that can be used when occasionally needed Point.h class Point { public: Point(const int x, const int y) : x_(x), y_(y) { } // ctor void CopyFrom(const Point& copy_from_me); ... Point(Point& copyme) = delete; // disable cctor Point& operator=(Point& rhs) = delete; // disable "=" private: ... }; // class Point sanepoint.cc Point x(1, 2); Point y(3, 4); x.CopyFrom(y); // OK // OK // OK

7 L12: C++ Class Details, Heap CSE333, Spring 2019 Access Control Access modifiers for members: public: accessible to all parts of the program private: accessible to the member functions of the class Private to class, not object instances protected: accessible to member functions of the class and any derived classes (subclasses more to come, later) Reminders: Access modifiers apply to all members that follow until another access modifier is reached If no access modifier is specified, struct members default to public and class members default to private 8 L12: C++ Class Details, Heap

CSE333, Spring 2019 Nonmember Functions Nonmember functions are just normal functions that happen to use some class Called like a regular function instead of as a member of a class object instance This gets a little weird when we talk about operators These do not have access to the class private members Useful nonmember functions often included as part of interface to a class Declaration goes in header file, but outside of class definition 9 L12: C++ Class Details, Heap CSE333, Spring 2019 friend Nonmember Functions

A class can give a nonmember function (or class) access to its non-public members by declaring it as a friend within its definition Not a class member, but has access privileges as if it were friend functions are usually unnecessary if your class includes appropriate getter public functions Complex.h class Complex { ... friend std::istream& operator>>(std::istream& in, Complex& a); ... }; // class Complex std::istream& operator>>(std::istream& in, Complex& a) { ... } Complex.cc 10 L12: C++ Class Details, Heap CSE333, Spring 2019 Namespaces Each namespace is a separate scope

Useful for avoiding symbol collisions! Namespace definition: namespace name name {{ namespace }} // declarations declarations go go here here // Creates a new namespace name if it did not exist, otherwise adds to the existing namespace (!) This means that components (e.g. classes, functions) of a namespace can be defined in multiple source files 11 L12: C++ Class Details, Heap CSE333, Spring 2019

Classes vs. Namespaces They seems somewhat similar, but classes are not namespaces: There are no instances/objects of a namespace; a namespace is just a group of logically-related things (classes, functions, etc.) To access a member of a namespace, you must use the fully qualified name (i.e. nsp_name::member) Unless you are using that namespace You only used the fully qualified name of a class member when you are defining it outside of the scope of the class definition 12 L12: C++ Class Details, Heap CSE333, Spring 2019 Complex Example Walkthrough See: Complex.h Complex.cc testcomplex.cc

13 L12: C++ Class Details, Heap CSE333, Spring 2019 Lecture Outline Class Details Filling in some gaps from last time Using the Heap new / delete / delete[] 14 L12: C++ Class Details, Heap CSE333, Spring 2019 C++11 nullptr C and C++ have long used NULL as a pointer value that references nothing

C++11 introduced a new literal for this: nullptr New reserved word Interchangeable with NULL for all practical purposes, but it has type T* for any/every T, and is not an integer value Avoids funny edge cases (see C++ references for details) Still can convert to/from integer 0 for tests, assignment, etc. Advice: prefer nullptr in C++11 code Though NULL will also be around for a long, long time 15 L12: C++ Class Details, Heap CSE333, Spring 2019 new/delete To allocate on the heap using C++, you use the new keyword instead of malloc() from stdlib.h

You can use new to allocate an object (e.g. new Point) You can use new to allocate a primitive type (e.g. new int) To deallocate a heap-allocated object or primitive, use the delete keyword instead of free() from stdlib.h Dont mix and match! Never free() something allocated with new Never delete something allocated with malloc() Careful if youre using a legacy C code library or module in C++ 16 L12: C++ Class Details, Heap CSE333, Spring 2019 new/delete Example int* AllocateInt(int x) { int* heapy_int = new int; *heapy_int = x; return heapy_int; }

Point* AllocatePoint(int x, int y) { Point* heapy_pt = new Point(x,y); return heapy_pt; } heappoint.cc #include "Point.h" using namespace std; ... // definitions of AllocateInt() and AllocatePoint() int main() { Point* x = AllocatePoint(1, 2); int* y = AllocateInt(3); cout << "x's x_ coord: " << x->get_x() << endl; cout << "y: " << y << ", *y: " << *y << endl; delete x; delete y; return EXIT_SUCCESS; } 17 L12: C++ Class Details, Heap CSE333, Spring 2019 Dynamically Allocated Arrays To dynamically allocate an array: Default initialize: type* name = new type[size]; To dynamically deallocate an array: delete[] Use delete[] name;name; It is an incorrect to use delete name; on an array The compiler probably wont catch this, though (!) because it cant always tell if name* was allocated with new type[size]; or new type; Especially inside a function where a pointer parameter could point to a single item or an array and theres no way to tell which! Result of wrong delete is undefined behavior 18 L12: C++ Class Details, Heap

CSE333, Spring 2019 Arrays Example (primitive) arrays.cc #include "Point.h" int main() { int stack_int; int* heap_int = new int; int* heap_int_init = new int(12); int stack_arr[3]; int* heap_arr = new int[3]; int* heap_arr_init_val = new int[3](); int* heap_arr_init_lst = new int[3]{4, 5}; // C++11 ... delete heap_int; delete heap_int_init; delete heap_arr; delete[] heap_arr_init_val; // // // //

return EXIT_SUCCESS; } 19 L12: C++ Class Details, Heap Arrays Example (class objects) CSE333, Spring 2019 arrays.cc #include "Point.h" int main() { ... Point stack_pt(1, 2); Point* heap_pt = new Point(1, 2); Point* heap_pt_arr_err = new Point[2]; Point* heap_pt_arr_init_lst = new Point[2]{{1, 2}, {3, 4}}; // C++11 ... delete heap_pt; delete[] heap_pt_arr_init_lst; return EXIT_SUCCESS; } 20

L12: C++ Class Details, Heap CSE333, Spring 2019 malloc vs. new malloc() new What is it? a function an operator or keyword How often used (in C)? often never How often used (in C++)? rarely often Allocated memory for

anything arrays, structs, objects, primitives Returns a void* (should be cast) appropriate pointer type (doesnt need a cast) When out of memory returns NULL throws an exception Deallocating free() delete or delete[] 21 L12: C++ Class Details, Heap

CSE333, Spring 2019 Dynamically Allocated Class Members What will happen when we invoke bar()? Vote at http://PollEv.com/justinh If there is an error, Foo::Foo(int how would you fix it? val) { Init(val); } Foo::~Foo() { delete foo_ptr_; } void Foo::Init(int val) { foo_ptr_ = new int; *foo_ptr_ = val; } A. B. C. D. E. Bad dereference Bad delete Memory leak Works fine Were lost

Foo& Foo::operator=(const Foo& rhs) { delete foo_ptr_; Init(*(rhs.foo_ptr_)); return *this; } void bar() { Foo a(10); Foo b(20); a = a; } 22 L12: C++ Class Details, Heap CSE333, Spring 2019 Heap Member Example Lets build a class to simulate some of the functionality of the C++ string Internal representation: c-string to hold characters What might we want to implement in the class?

23 L12: C++ Class Details, Heap Str Class Walkthrough CSE333, Spring 2019 Str.h #include using namespace std; class Str { public: Str(); Str(const char* s); Str(const Str& s); ~Str(); // // // // default ctor c-string ctor copy ctor dtor

int length() const; // return length of string char* c_str() const; // return a copy of st_ void append(const Str& s); Str& operator=(const Str& s); // string assignment friend std::ostream& operator<<(std::ostream& out, const Str& s); private: char* st_; // c-string on heap (terminated by '\0') }; // class Str 24 L12: C++ Class Details, Heap CSE333, Spring 2019 Str::append Complete the append() member function: char* strcpy(char* dst, const char* src); char* strcat(char* dst, const char* src); #include #include "Str.h" // append contents of s to the end of this string void Str::append(const Str& s) { }

25 L12: C++ Class Details, Heap CSE333, Spring 2019 Extra Exercise #1 Write a C++ function that: Uses new to dynamically allocate an array of strings and uses delete[] to free it Uses new to dynamically allocate an array of pointers to strings Assign each entry of the array to a string allocated using new Cleans up before exiting Use delete to delete each allocated string Uses delete[] to delete the string pointer array (whew!) 26

Recently Viewed Presentations

  • Master of Arts

    Master of Arts

    c) No adjustment for US: E.g. US could not reduce value of currency. Other countries take advantage Trade Convertibility 2) Globalization: Growth of short term financial flows/eroding of capital controls (1970s) E.g. "Euromarkets" Increased pressure on fixed exchange rates Major...
  • Postmodernism(s) - Home | UBC Blogs

    Postmodernism(s) - Home | UBC Blogs

    Hybridity, pastiche,bricolage. Hypermedia, Internet, as transcendence of physical limits of print media. Postmodernism rejects both the "Civilization" view of culture, defined by Matthew Arnold as "The best that has been thought and said" as well as the "high/low" divide exacerbated...
  • Closing the Gaps - Reducing Inequalities in Educational Outcomes

    Closing the Gaps - Reducing Inequalities in Educational Outcomes

    closing the gaps - reducing inequalities in educational outcomes birmingham achievement group seminar january 2007 john hill research& statistics
  • Disorders of Red Blood Cells - Physiology for Medical Students

    Disorders of Red Blood Cells - Physiology for Medical Students

    HaemolyticAnemias. Intravascular haemolysis is less common, caused by complement fixation in transfusion reactions, mechanical injury or toxic factors. Extravascular haemolysis . occurs when RBCs are less deformable to traverse splenic sinusoids, characterized by anemia and jaundice
  • Degenerate stars There is not a sharp transition

    Degenerate stars There is not a sharp transition

    Degenerate stars There is not a sharp transition between relativistically degenerate and non-relativistically degenerate gas. Similarly there is no sharp transition between an ideal gas and a completely degenerate one. Partial degeneracy situation requires much more complex solution. White dwarfs...
  • Progress in Adult Immunization Composite Measure

    Progress in Adult Immunization Composite Measure

    Background. Opioid prescriptions have risen dramatically over the past 15-20 years. 1 in 4 receiving long-term opioid therapy, in primary care settings, struggle with opioid addiction
  • Mystery Powers - pdsd.org

    Mystery Powers - pdsd.org

    Mystery Powders. During this unit we will not use the sense of taste. Unless you are working in a Test Kitchen taste is not safe in the laboratory.
  • The Three Fundamental Chemical Laws Law of Conservation

    The Three Fundamental Chemical Laws Law of Conservation

    Big Idea #1: Know this well!!! aluminum oxide tetraphosphorous decoxide mercury(II) sulfide hydrogen chlorate chloric acid Al2O3 P4O10 HgS HClO3 HClO3(aq) Title Author