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;
}
在调用虚拟函数时,我遇到了"访问冲突"
我很惊讶为什么虚拟函数会崩溃?
通过观察,我可以看到虚拟指针在分配后已损坏。但我很好奇为什么这会被破坏。
您的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
相关文章:
- C++无法定义虚拟函数 OUTER 类和头文件
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- 当覆盖存在时调用基本虚拟"binded to object"函数
- 如何在C++中伪造虚拟可变参数函数模板?
- 类型擦除的std::function与虚拟函数调用的开销
- 重写虚拟函数和继承
- 是否可以使用函数指针调用虚拟析构函数?
- 在没有动态内存的世界中,我是否需要虚拟析构函数?
- 虚拟继承基构造函数消除
- "虚拟""覆盖"析构函数
- 类中的虚拟布尔函数参数不起作用
- 用纯虚拟函数兜圈子
- 将C++子类成员函数(虚拟实现)传递给 C 类型函数指针
- 尝试在 QLabel 上绘画失败(无法在没有对象的情况下调用成员函数"虚拟无效 QLabel::p aintEvent(QPaintEvent*)")
- 声明析构函数虚拟就足够了吗?
- 视觉 C++当我们在基类中使函数成为纯虚拟时,那么在子类中再次使相同的函数虚拟的必要性是什么
- 重载函数(虚拟/非虚拟)