C++ 具有虚拟和非虚拟函数的唯一_ptr::get()函数

C++ 具有虚拟和非虚拟函数的唯一_ptr::get()函数,c++,c++11,unique-ptr,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::

我正在使用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;
}
xyz类{
公众:
虚拟int getm();
int get();
静态std::unique_ptr returnbase();
};
abc类:公共xyz
{
公众:
int getm(){return 0;}
};
std::unique_ptr xyz::returnbase()
{
std::唯一的\u ptr u\u Swift(nullptr);
u_Swift=std::unique_ptr(动态_cast(new abc());
返回u_Swift;
}
int _tmain(int argc,_TCHAR*argv[]
{
xyz*x1=xyz::returnbase().get();
x1->get();
x1->getm();
返回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
intmain()
{
std::unique_ptr thing=xyz::returnbase();
xyz*x1=thing.get();
//…使用x1和*x1。。。
}//东西超出了范围,*东西被破坏了

您的
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
intmain()
{
std::unique_ptr thing=xyz::returnbase();
xyz*x1=thing.get();
//…使用x1和*x1。。。
}//东西超出了范围,*东西被破坏了

为什么要编写如此冗长的代码?例如,
returnbase()
应该由一条语句组成:
returnstd::unique_ptr(dynamic_cast(new xyz())
new xyz()
转换为
xyz*
有什么意义?它已经是一个
xyz*
。这个问题与虚拟函数无关。@KerrekSB:No:
return std::make_unique()
@Nipun您也不需要将
动态\u cast
转换为基类。为什么要编写如此冗长的代码?例如,
returnbase()
应该由一条语句组成:
returnstd::unique_ptr(dynamic_cast(new xyz())
new xyz()
转换为
xyz*
有什么意义?它已经是一个
xyz*
。这个问题与虚拟函数无关。@KerrekSB:No:
return std::make_unique()
@Nipun您也不需要对基类进行
dynamic\u cast