mardi 23 juin 2015

unique_ptr::get() function with virtual and non-virtual function

I am using VS2012.
I am porting code from raw pointer to unique_ptr and facing a problem.
Here I have tried to simulate the scenario:

class xyz{
  public:
    virtual int getm();
    int get();       
    static std::unique_ptr<xyz> returnbase();
};

std::unique_ptr<xyz> xyz::returnbase()
{
    std::unique_ptr<xyz> u_Swift(nullptr);
    u_Swift =  std::unique_ptr<xyz>(dynamic_cast<xyz*>(new xyz()));
    return u_Swift;
}

int _tmain(int argc, _TCHAR* argv[])
{
    xyz* x1 = xyz::returnbase().get();
    x1->get();
    x1->getm();
    return 0;
}

I get a crash "Access Violation" while calling virtual function.
I am surprised why this is crashing for virtual functions?

Thru watch I can see that virtual pointer is corrupted after assignment. But why this is corrupted, I am curious about.

Aucun commentaire:

Enregistrer un commentaire