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

时间:2015-06-23 09:39:30

标签: c++ c++11 unique-ptr

我正在使用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;
}

我在调用虚拟功能时遇到“访问冲突”崩溃 我很惊讶为什么这会导致虚函数崩溃?

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

1 个答案:

答案 0 :(得分:6)

你的x1是一个悬空指针,因为拥有其初始指针的临时唯一指针在main的第一个语句的末尾被销毁,因此指针被销毁。 / p>

 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
相关问题