While going into C++ in depth, I am working on shallow/deep copying. According to the MOOC I'm following, the following code should crash,
// .hpp file
#ifndef _COPY_HPP_
#define __COPY_HPP_
class Shallow {
private:
int* data;
public:
void setData (int d){ *data = d;}
int getData(){ return *data;}
// constructor
Shallow (int d);
// copy constructor
Shallow(const Shallow &source);
//destructor
~Shallow();
};
#endif
// .cpp file
#include "copy.hpp"
#include<stdio.h>
#include<iostream>
using namespace std;
Shallow::Shallow(int d){
data = new int;
*data = d;
}
void displayShallow(Shallow s){
cout << "displayShallow: " << s.getData() << "\n";
}
Shallow::Shallow(const Shallow &source)
: data{source.data} {
cout << "copy constructor call" << "\n";
}
Shallow::~Shallow(){
delete data;
cout << "freeing data" << "\n";
}
int main(){
Shallow original{100};
cout << original.getData() << "\n";
// destructor called after this call
displayShallow(original);
cout << original.getData() << "\n";
original.setData(29);
cout << original.getData() << "\n";
return 0;
}
as (into displayShallow()
) "the destructor is called and the destructor releases the storage it is pointing to in the heap. The object that was copied into this function still points to this now released storage but it thinks that the storage is valid so all kinds of bad things can happen."
When the "teacher" runs this code, his program crashes while I get:
100
copy constructor call
displayShallow: 100
freeing data
0
29
freeing data
It seems that the storage to which data
points to is set to 0
instead of crashing. Do I understand this correctly?