dimanche 27 juin 2021

Implement the custom move constructor and assignment for my problem

I wrote the c++ code, because im learning c++ and practicing struct, class, move ctr, copy constructor, inheritance, unique pointer, etc. however, It provided me the following problem that x3 and rrr are suffering from linkage issue, means, it is just a simple copy by value and both pointers are pointing to the same memory location. I dont know how to implement the custom move constructor and assignment for my problem to solve this issue?

#include <iostream>
#include<memory>


struct family{
    int x{};
    int y{};
    int z{};

    void show();
    family();
    ~family();
    family(int i, int j, int k);


    family& operator = (const family& v); //l -value ref
    family& operator=(family&& v);

};


void family::show(){
    std::cout<< x << y << z <<std::endl;
}

family::family(int i, int j, int k)
:x{i},y{j},z{k}
{std::cout << "custom ctor\n";}

family::family()=default;
family::~family()= default;


struct family2{
    int xx{};
    int yy{};
    virtual void show() const noexcept { std::cout << "Bau\n"; }
    family2();
    ~family2();
    family2(  int f,  int g);
    
};


family2::family2()=default;
family2::~family2()= default;
family2::family2(  int f,  int g) : xx{f},yy{g}{}


struct pr : public family2{
    pr() = default;
    ~pr()= default;
    pr(  int xx,  int yy) : family2{xx, yy} {}
    void show() const noexcept override { std::cout << "mau\n"; }

};

int main(){

family kkk{1,2,3};
kkk.show();

family lll;
lll.x= 8;
lll.show();


auto ooo= std::make_unique< family> (7,8,9);
ooo->show();


std::unique_ptr <family> unq (new family (88,88,88));
//std::unique_ptr <family> ppp (88,88,88); error
unq->show();

std::unique_ptr <family >unq2 (std::move(unq));
unq2->show();

unq.reset(new family(9,9,90));
unq->show();


family *uu = unq.release();
//uu->x= 999999;
uu->show();

if(unq == nullptr)
    std::cout<< "oooo" <<std::endl;

 family2* rrr = new pr{11, 11};  // daynamic polymorphysem
    std::cout << "through pointer\n";
    rrr->show();

family2 *x3{std::move(rrr)};  // move ctor
x3->show();

}


Aucun commentaire:

Enregistrer un commentaire