unique_ptr::get() 具有虚函数和非虚函数的函数
unique_ptr::get() function with virtual and non-virtual function
我正在使用 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;
}
我在调用虚函数时遇到崩溃 "Access Violation"。
我很惊讶为什么这会导致虚函数崩溃?
通过观察,我可以看到虚拟指针在分配后已损坏。但是这个为什么会损坏,我很好奇。
你的 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
我正在使用 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;
}
我在调用虚函数时遇到崩溃 "Access Violation"。
我很惊讶为什么这会导致虚函数崩溃?
通过观察,我可以看到虚拟指针在分配后已损坏。但是这个为什么会损坏,我很好奇。
你的 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