[PDF] [PDF] CSE 374 - Week 8 (Wed) C++: RAII, Constructors, Destructors

C++: RAII, Constructors, Destructors In C++, struct and class are (nearly) the same C++ will automatically create a synthesized default constructor if



Previous PDF Next PDF





[PDF] Adding methods() to structures in C - Open-std

18 mar 2014 · 8 3 Destructors 2 A destructor is used to destroy objects of its struct type The destructor takes no parameters, and no return type (void, int, double, string, etc) may be specified A destructor can be invoked for a const or volatile object, but it cannot be declared const nor volatile



Classes and Structs

Instead of just the C++ destructor, C++/CLI classes may have a destructor and/or a finalizer to handle cleanup You'll see how these behave, how destructors 



[PDF] Composite objects: structs and classes - INFN Sezione di Padova

Plain-C structs contain only variables or other objects, C++ classes provide several new functionalities: constructor(s) and destructor, functions handling data  



[PDF] Welcome to Introduction to Object-Oriented Programming (OO

A large segment of C bugs occur when the programmer forgets to programmers don't know how to initialize a struct, or The destructor is called automatically



[PDF] Linked List Class

to Classes Today ○ Why not C struct? Why C++ class? ○ C++ Classes ○ C++ Information Hiding - Public and Private ○ Constructors ○ Destructors 



[PDF] Practical C++ Decompilation

Dealing with C++ in IDA and Hex-Rays decompiler Equivalent structure can be produced by removing all c) call destructors of complex class members



[PDF] Structs, Classes, the Heap & the Stack - Code Liberation

Until now we have been using objects created by c++ for us Structs Structs 1) The destructor must have the same name as the class, preceded by a tilde (~)



[PDF] CSE 374 - Week 8 (Wed) C++: RAII, Constructors, Destructors

C++: RAII, Constructors, Destructors In C++, struct and class are (nearly) the same C++ will automatically create a synthesized default constructor if



[PDF] CLASSES

Destructor 3 6 Sample Application: A Task Class 3 7 Class Data Members Although either of the keywords class and struct may be used to declare a C++

[PDF] structo crete screws

[PDF] structural analysis 1 pdf notes

[PDF] structural design patterns pdf

[PDF] structural explanation of health inequalities

[PDF] structural formula of carboxylic acid

[PDF] structural functionalism in family

[PDF] structural organisation of proteins pdf

[PDF] structural queries

[PDF] structural queries in information retrieval

[PDF] structure and function of nucleic acids pdf

[PDF] structure and union in c geeksforgeeks

[PDF] structure de données pdf

[PDF] structure de l'atome cours 3ème pdf

[PDF] structure électronique de l'atome cours pdf

[PDF] structure exercises in c

CSE 374 -Summer 2020

CSE 374 -Week 8 (Wed)

C++: RAII, Constructors, Destructors

Instructor: Andrew Hu

TAs: Jim Limprasert, Kaelin Laundry, Keith Jiang, Nick Durand,

Simon McFarlane, Yitian Hao

1

CSE 374 -Summer 2020

Plan for the Week

żOperator overloading

żReferences

żClasses

żRAII philosophy

żConstructors & Destructors

żnew/delete

żTemplates

żSTL, smart pointers2

CSE 374 -Summer 2020

Class Definition (.hfile)

3 #ifndef POINT_H_ #define POINT_H_ classPoint { public:

Point(intx, inty); // constructor

intget_x() const { returnx_; } // inline member function int get_y() const { returny_; } // inline member function double Distance(const Point&p) const; // member function void SetLocation(intx, inty); // member function private: int x_; // data member int y_; // data member }; // class Point #endif// POINT_H_

Point.h

CSE 374 -Summer 2020

Class Member Definitions (.ccfile)

4 #include #include "Point.h"

Point::Point(const int x, const int y){

x_ = x; this->y_ = y; // "this->" is optional unless name conflicts double Point::Distance(const Point&p) const { // get_x(), get_y() accessor functions or the x_, y_ private // function of the same class. doubledistance = (x_ -p.get_x()) * (x_ -p.get_x()); distance += (y_ -p.y_) * (y_ -p.y_); returnsqrt(distance); void Point::SetLocation(const intx, const inty) { x_ = x; y_ = y;

Point.cc

CSE 374 -Summer 2020

Class Usage (.ccfile)

5 #include #include #include "Point.h" using namespacestd; int main(intargc, char** argv) { Point p1(1, 2); // allocate a new Point on the Stack Point p2(4, 6); // allocate a new Point on the Stack cout << "p1 is: ("<< p1.get_x() << ", "; cout << p1.get_y() << ")"<< endl; cout << "p2 is: ("<< p2.get_x() << ", "; cout << p2.get_y() << ")"<< endl; cout << "dist : "<< p1.Distance(p2) << endl; returnEXIT_SUCCESS; usepoint.cc

CSE 374 -Summer 2020

structvs. class żNo methods and all fields are always accessible

żBoth can have methods and member visibility

(public/private/protected) żMinor difference: members are default publicin a structand default privatein a class

żUse structfor simple bundles of data

żUse classfor abstractions with data + functions 6 STYLE TIP

CSE 374 -Summer 2020

RAII

żCreate = constructor

żAcquire = allocate (e.g. memory, files)

żDestroy = destructor

żRelease = deallocate

7

CSE 374 -Summer 2020

RAII Example

8 char* return_msg_c() { intsize = strlen("hello") + 1; char* str = malloc(size); strncpy(str, "hello", size); returnstr; std::string return_msg_cpp() { std::string str("hello"); returnstr; usingnamespacestd; char* s1 = return_msg_c(); cout << s1 << endl; string s2 = return_msg_cpp(); cout << s2 << endl;

CSE 374 -Summer 2020

Lecture Outline

9

CSE 374 -Summer 2020

Constructors

object żA class can have multiple constructors that differ in parameters żC++ will automatically create a synthesized default constructor if you have nouser-defined constructors (non-POD) member variables reference data members 10

Point(const intx, const inty);

CSE 374 -Summer 2020

Synthesized Default Constructor

11 classSimplePoint { public: // no constructors declared! intget_x() const { returnx_; } // inline member function int get_y() const { returny_; } // inline member function double Distance(const SimplePoint&p) const; void SetLocation(intx, inty); private: int x_; // data member int y_; // data member }; // class SimplePointSimplePoint.h #include"SimplePoint.h" ... // definitions for Distance() and SetLocation() intmain(int argc, char** argv) { SimplePoint x;// invokes synthesized default constructor returnEXIT_SUCCESS;

SimplePoint.cc

CSE 374 -Summer 2020

Synthesized Default Constructor

defined all the ones you intend to be available and will notadd any others 12 #include"SimplePoint.h" // defining a constructor with two arguments SimplePoint::SimplePoint(const intx, const inty) { x_ = x; y_ = y; voidfoo() { SimplePoint x;// compiler error: if you define any // ctors, C++ will NOT synthesize a // default constructor for you. SimplePoint y(1, 2); // works: invokes the 2-int-arguments // constructor

CSE 374 -Summer 2020

Multiple Constructors (overloading)

13 #include"SimplePoint.h" // default constructor

SimplePoint::SimplePoint() {

x_ = 0; y_ = 0; // constructor with two arguments SimplePoint::SimplePoint(const intx, const inty) { x_ = x; y_ = y; voidfoo() {

SimplePoint x;// invokes the defaultconstructor

SimplePoint y(1, 2); // invokes the 2-int-argumentsctor SimplePoint a[3]; // invokes the default ctor 3 times

CSE 374 -Summer 2020

Initialization Lists

part of a constructor definition żInitializes fields according to parameters in the list

żThe following two are (nearly) identical:

14 // constructor with an initialization list Point::Point(const intx, const inty) : x_(x), y_(y){ std::cout << "Point constructed: ("<< x_ << ","; std::cout << y_<< ")"<< std::endl;

Point::Point(const intx, const inty) {

x_ = x; y_ = y; std::cout << "Point constructed: ("<< x_ << ","; std::cout << y_<< ")"<< std::endl;

CSE 374 -Summer 2020

Initialization vs. Construction

żData members in initializer list are initialized in the order they are defined in the class, not by the initialization list ordering (!) initialized/constructedbefore body is executed żInitialization preferred to assignment to avoid extra steps classPoint3D { public: // constructor with 3 int arguments Point3D(const intx, const inty, const intz) : y_(y), x_(x) { z_ = z; private: int x_, y_, z_; // data members }; // class Point3D

First, initialization list is applied.

Next, constructor body is executed.

STYLE TIP

CSE 374 -Summer 2020

Lecture Outline

16

CSE 374 -Summer 2020

Copy Constructors

żUsed to create a new object as a copy of an existing object 17 Point::Point(const intx, const inty) : x_(x), y_(y) { } // copy constructor

Point::Point(const Point©me) {

x_ = copyme.x_; y_ = copyme.y_; voidfoo() { Point x(1, 2); // invokes the 2-int-arguments constructor

Point y(x);// invokes the copy constructor

Point z = y;// also invokes the copy constructor

STYLE TIP

CSE 374 -Summer 2020

Synthesized Copy Constructor

synthesize one for you żIt will do a shallowcopy of all of the fields (i.e.member variables) of your class żSometimes the right thing; sometimes the wrong thing 18 #include"SimplePoint.h" ... // definitions for Distance() and SetLocation() intmain(int argc, char** argv) {

SimplePoint x;

SimplePoint y(x); // invokes synthesized copy constructor returnEXIT_SUCCESS;

CSE 374 -Summer 2020

When Do Copies Happen?

żYou initializean object from

another object of the same type:

żYou pass a non-reference

object as a value parameter to a function:

żYou return a non-reference

object value from a function: 19 voidfoo(Point x) { ... }

Point y; // default ctor

foo(y);// copy ctor

Point x; // default ctor

Point y(x); // copy ctor

Point z = y; // copy ctor

Pointfoo() {

Point y; // default ctor

returny;// copy ctor

CSE 374 -Summer 2020

Compiler Optimization

unnecessary copies żSometimes you might not see a constructor get invoked when you might expect it 20

Pointfoo() {

Point y; // default ctor

returny;// copy ctor? optimized?

Point x(1, 2); // two-ints-argument ctor

Point y = x; // copy ctor

Point z = foo(); // copy ctor? optimized?

CSE 374 -Summer 2020

Lecture Outline

21

CSE 374 -Summer 2020

Assignment != Construction

żAssigns values to an existing, already constructedobject 22

Point w; // default ctor

Point x(1, 2); // two-ints-argument ctor

Point y(x); // copy ctor

Point z = w; // copy ctor

y = x; // assignment operator

CSE 374 -Summer 2020

żBut there are some rules you should follow:

23

Point&Point::operator=(const Point&rhs) {

if(this!= &rhs) { // (1)always check against this x_ = rhs.x_; y_ = rhs.y_; return*this; // (2)always return *this from op=

Pointa; // default constructor

a = b = c; // works because = return *this a = (b = c); // equiv. to above (= is right-associative) (a = b) = c; // "works" because = returns a non-const STYLE TIP

CSE 374 -Summer 2020

Synthesized Assignment Operator

synthesize one for you żIt will do a shallowcopy of all of the fields (i.e.member variables) of your class żSometimes the right thing; sometimes the wrong thing 24
#include"SimplePoint.h" ... // definitions for Distance() and SetLocation() intmain(int argc, char** argv) {

SimplePoint x;

SimplePoint y(x);

y = x; // invokes synthesized assignment operator returnEXIT_SUCCESS;

CSE 374 -Summer 2020

Lecture Outline

25

CSE 374 -Summer 2020

Destructors

żInvoked automatically when a class instance is deleted, goes out of scope, etc. (even via exceptions or other causes!) żPlace to put your cleanup code Ҍfree any dynamic storage or other resources owned by the object żStandard C++ idiom for managing dynamic resources 26

Point::~Point(){ // destructor

// do any cleanup needed when a Point object goes away // (nothing to do here since we have no dynamic resources)

CSE 374 -Summer 2020

Poll Question: PollEv.com/andrewhu

27

CSE 374 -Summer 2020

Polling Question

żAssume Pointwith everything defined (ctor, cctor, =, dtor)

żAssume no compiler optimizations

A.1 B.2 C.3 D.4 28

Point PrintRad(Point& pt) {

Pointorigin(0, 0);

doubler = origin.Distance(pt); doubletheta = atan2(pt.get_y(), pt.get_x()); cout << "r = " << r << endl; cout << "theta = " << theta << " rad" << endl; returnpt; int main(intargc, char** argv) {

Pointpt(3, 4);

PrintRad(pt);

return0; test.cc

CSE 374 -Summer 2020

Demo: Tracer

29

CSE 374 -Summer 2020

Rule of Three

1)Destructor

2)Copy Constructor

3)Assignment (operator=)

żCan explicitly ask for default synthesized versions (C++11): 30
classPoint { public: Point() = default; // the default ctor ~Point() = default; // the default dtor Point(constPoint©me) = default; // the default cctor Point& operator=(constPoint& rhs) = default; // the default "="

CSE 374 -Summer 2020

Dealing with the Insanity (C++11)

żDisablingthe copy constructor and assignment operator can avoid confusion from implicit invocation and excessive copying 31
classPoint { public: Point(const intx, const inty) : x_(x), y_(y) { } // ctor Point(constPoint©me) = delete; // declare cctor and "=" as Point& operator=(const Point& rhs) = delete; // as deleted (C++11) private: }; // class Point Point w; // compiler error (no default constructor)

Point x(1, 2); // OK!

Point y = w; // compiler error (no copy constructor) y = x; // compiler error (no assignment operator)

Point_2011.h

CSE 374 -Summer 2020

Clone żIf you disable them, then you instead may want an explicit 32
classPoint { public: Point(const intx, const inty) : x_(x), y_(y) { } // ctor void Clone(const Point& copy_from_me); Point(Point©me) = delete; // disable cctor Point& operator=(Point& rhs) = delete; // disable "=" private: }; // class Point

Point_2011.h

Point x(1, 2); // OK

Point y(3, 4); // OK

x.Clone(y); // OK sanepoint.cc

CSE 374 -Summer 2020

Access Control

żpublic: accessible to allparts of the program

żprivate: accessible to the member functions of the class żprotected: accessible to member functions of the class and any derivedclasses (subclasses Ҍmore to come, later) żAccess modifiers apply to allmembers that follow until another access modifier is reached żIf no access modifier is specified, structmembers default to publicand classmembers default to private 33

CSE 374 -Summer 2020

Nonmember Functions

happen to use some class żCalled like a regular function instead of as a member of a class object instance

żThese do notҁ

interface to a class żDeclaration goes in header file, but outsideof class definition 34

CSE 374 -Summer 2020

friendNonmember Functions to its non-publicmembers by declaring it as a friendwithin its definition żNot a class member, but has access privileges as if it were żfriendfunctions are usually unnecessary if your class includes 35
classComplex{ friendstd::istream&operator>>(std::istream&in, Complex&a); }; // class Complex std::istream&operator>>(std::istream&in, Complex&a) {

Complex.h

Complex.cc

CSE 374 -Summer 2020

Namespaces

żUseful for avoiding symbol collisions!

żnamespacename {

// declarations go here indentation of its contents żCreates a new namespace name if it did not exist, otherwise adds to the existing namespace(!) defined in multiple source files36 namespacename { // declarations go here } // namespace name

CSE 374 -Summer 2020

Classes vs. Namespaces

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) defining it outside of the scope of the class definition 37

CSE 374 -Summer 2020

C++11 nullptr

references nothing

żNew reserved word

żInterchangeable with NULLfor all practical purposes, but it has type T*for any/every T, and is not an integer value

żAdvice: prefer nullptrin C++11 code

39

CSE 374 -Summer 2020

new/delete keyword instead of malloc()from stdlib.h żYou can use new to allocate an object (e.g.newPoint) żYou can use new to allocate a primitive type (e.g.newint) the deletekeyword instead of free()from stdlib.h 40

CSE 374 -Summer 2020

new/deleteExample 41
#include"Point.h" ... // definitions of AllocateInt() and AllocatePoint() intmain() {

Point* x = AllocatePoint(1, 2);

int* y = AllocateInt(3); cout << "x's x_ coord: "<< x->get_x() << endl; cout << "y: " << y << ", *y: " << *y << endl; deletex; deletey; returnEXIT_SUCCESS; int* AllocateInt(int x) { int* heapy_int = newint; *heapy_int = x; returnheapy_int;

Point* AllocatePoint(int x, inty) {

Point* heapy_pt = newPoint(x,y);

returnheapy_pt; heappoint.cc

CSE 374 -Summer 2020

Dynamically Allocated Arrays

żDefault initialize:

żUse delete[] name;

quotesdbs_dbs17.pdfusesText_23