mercredi 21 août 2019

Constructor and copy constructors

I have started studying C++ after some years in C# and other languages. I am facing the class arguments (constructors, inheritance, copy etc) and I was trying to write a bad sample code. Below is a sample class (.h and .cpp):

#ifndef SAMPLE_H
#define SAMPLE_H

#include <iostream>

class Sample
{
    public:
        Sample();
        //Sample(const Sample& s);
        virtual ~Sample();
        int *s_array;
    protected:

    private:

};

void print(const Sample *s);

#endif // SAMPLE_H

Sample::Sample()
{
    std::cout<<"create sample\n";
    s_array=new int[10];
    std::cout<<"alloc memory 10 int array\n";

    for(int i=0; i<10; ++i)
    {
        s_array[i]=i;
    }
}

Sample::~Sample()
{
    //dtor
    std::cout<<"Dealloc memory 10 int array\n";
    delete [] s_array;
    std::cout<<"destroy sample\n";
}

void print(const Sample *s)
{
    std::cout<<s<<" "<<s->s_array<<'\n';

    for(int i=0; i<10; ++i)
    {
        std::cout<<s->s_array[i]<<" ";
    }
    std::cout<<"\n\n";
}

Then in main

#include <iostream>
#include "Sample.h"

using namespace std;

int main()
{
    cout<<endl<<"Let's try the Copy const WRONG....  "<<endl;
    Sample *s1=new Sample();
    print(s1);
    Sample s2(*s1);
    cout<<endl<<"What is s2 ???  "<<endl;
    print(&s2);
    delete s1;
    cout<<endl<<"What is s2 NOW after s1 delete???  "<<endl;
    print(&s2);
    return 0;
}

I wanted to test the dangers of NOT to use the copy constr and i expected to see after the deletion of s1 a totally 'dirty' array (i.e., 10 random values or even a crash) This is the output I gain (Win 10 pro, IDE CodeBlock, GNU Gcc compiler): Let's try the Copy const WRONG.... create sample alloc memory 10 int array 0x1ba110 0x1b6e48 0 1 2 3 4 5 6 7 8 9

What is s2 ??? 0x6efdf0 0x1b6e48 0 1 2 3 4 5 6 7 8 9

Dealloc memory 10 int array destroy sample

What is s2 NOW after s1 delete??? 0x6efdf0 0x1b6e48 1812296 1769664 2 3 4 5 6 7 8 9

Dealloc memory 10 int array destroy sample

Why only the first two items of s_array are 'dirty' and the remaining 8 are good? Why the deletion of object s1 does not free the whole memory pointed by s2? Thanx in advance Diego

Aucun commentaire:

Enregistrer un commentaire