unique_ptr::get()函数,具有虚拟和非虚拟函数

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

本文关键字:函数 虚拟 ptr get unique      更新时间:2023-10-16

我正在使用VS2012。
我正在将代码从原始指针移植到unique_ptr,并面临一个问题
在这里,我尝试模拟场景:

class xyz{
  public:
    virtual int getm();
    int get();       
    static std::unique_ptr<xyz> returnbase();
};
class abc:public xyz
{
public:
    int getm() {return 0;}
};
std::unique_ptr<xyz> xyz::returnbase()
{
    std::unique_ptr<xyz> u_Swift(nullptr);
    u_Swift =  std::unique_ptr<xyz>(dynamic_cast<xyz*>(new abc()));
    return u_Swift;
}
int _tmain(int argc, _TCHAR* argv[])
{
    xyz* x1 = xyz::returnbase().get();
    x1->get();
    x1->getm();
    return 0;
}

在调用虚拟函数时,我遇到了"访问冲突"
我很惊讶为什么虚拟函数会崩溃?

通过观察,我可以看到虚拟指针在分配后已损坏。但我很好奇为什么这会被破坏。

您的x1是一个悬空指针,因为拥有其初始指针对象的临时唯一指针在main的第一个语句结束时被销毁,因此指针对象也被销毁。

 xyz* x1 = xyz::returnbase().get();
 //        ^^^^^^^^^^^^^^^^^      ^^
 //         temporary object       ^-- destroyed here

要保留对象,您需要使其成为非临时的,如以下所示:

int main()
{
    std::unique_ptr<xyz> thing = xyz::returnbase();
    xyz * x1 = thing.get();
    // ... use x1 and *x1 ...
}  // thing goes out of scope and *thing is destroyed