new and delete
12.1 new and delete
#include<iostream>
using namespace std;
class Base{
public:
Base(int x, int y){cout<<x<<", "<<y<<"\n";}
~Base(){cout<<"Base destructs\n";}
};
int main(){
Base *b=new Base[2]{{1,2},{3,4}};
delete[] b;
return 0;
}
12.2 Shallow copy
copy address of a pointer
12.3 Deep copy
copy all data members
13.1. copy
##Copy constructor
#include <iostream>
using namespace std;
class Base{
public:
int *ptr;
Base(){
ptr=new int(1);
}
Base(const Base &b){//copy constructor overloading
ptr=new int(*(b.ptr));
}
~Base(){
delete ptr;
}
};
int main(){
Base B1, B2=B1;
cout<<B1.ptr<<" value:"<<*(B1.ptr)<<endl;
cout<<B2.ptr<<" value:"<<*(B2.ptr)<<endl;
while (1){
Base B3;
}
return 0;
}
Copy constructor of derived class
#include <iostream>
using namespace std;
class Base{
public:
Base(){
cout<<"base construct\n";
}
virtual ~Base(){
cout<<"base destruct\n";
}
};
class Derived: public Base{
public:
int *ptr;
Derived(){
ptr=new int(1);
cout<<"derived construct\n";
}
Derived(const Derived &d){//copy constructor overloading
ptr=new int(*(d.ptr));
cout<<"derived copy construct "<<ptr<<endl;
}
~Derived(){
cout<<"derived destruct "<<ptr<<endl;
delete ptr;
}
};
int main(){
Derived D1;
while (1){
Base *D2 = new Derived(D1);
delete D2;
}
return 0;
}
13.2. this
refer to current pointer of
13.3. assignment operator overloading
see section 5.2
13.4. new and delete with an object in a class
don't forget to destruct the allocated memory to prevent memory leaks.
13.5 new/delete and new[]/delete[]
When an instance is allocated by new, it must be deallocated by delete. Similarly, array-like allocation must use new[] with delete[].
You may try to use new[] with delete (without[]). But this will lead to undefined behavior that means possibility for memory leaking.
Try to run and change the following code;
#include<iostream>
using namespace std;
class A{
public:
int* p;
A(){
p=new int[10];
}
~A(){
delete[] p;
}
};
class B{
public:
A *p;
B(){
p=new A[10];
}
~B(){
delete[] p;
}
};
int main(){
while(1){
B b;
}
}