【问题标题】:How can I downcast a pointer after passing it through a function?将指针传递给函数后如何向下转换?
【发布时间】:2019-06-25 13:04:57
【问题描述】:

我创建了一个函数,它返回指向在 func 中创建的派生对象的基指针。 好像不行啊!好像派生的数据丢失了,指针指向一个基础对象……

有一个类Request,它是基类, 并且有类 loginRequest - 它派生请求。为了检查对象的类型,我打印了对象的名称 (typeid(*r).name())。 在 func() 内部,打印输出结果是“loginRequest”,这很好,因为这是指向的对象。 (看代码) 但是在返回这个指针之后,当我再次打印它的类型时,结果是“请求”。你们能帮帮我吗?为什么返回的指针会丢失派生数据?


Request * r = new Request();
r = func(); // r is now supposed to point the LoginRequest object.
std::cout<< typeid(*r).name() <<std::endl; //print the type of OBJECT

//func
Request * func()
{
    Request * r;
    LoginRequest l = LoginRequest();
    r = &l;
    std::cout<< typeid(*r).name() <<std::endl;  //print the type of OBJECT
    return r; 
}

【问题讨论】:

  • 你的对象是本地的;一旦函数返回,它就消失了。
  • 对象“LoginRequest l”?那我该怎么办?
  • 按值返回或返回一个指向动态分配的(智能)指针。
  • 请不要使用new。使用std::unique_ptr

标签: c++ function polymorphism downcast


【解决方案1】:

您正在返回一个指向对象 l 的指针,该对象具有自动存储持续时间。
取消引用返回的指针具有未定义的行为。

您需要使用new 动态创建该对象,并消除因在函数外滥用new 而导致的内存泄漏:

Request* func()
{
    Request* r = new LoginRequest();
    std::cout<< typeid(*r).name() <<std::endl;  //print the type of OBJECT
    return r; 
}


// ...

Request * r = func();
std::cout << typeid(*r).name() << std::endl; //print the type of OBJECT

【讨论】:

    【解决方案2】:

    您正在创建一个本地 LoginRequest 对象:

    LoginRequest l = LoginRequest();
    

    获取该地址:

    r = &l;
    

    并返回它:

    return r;
    

    l 超出了下一行的范围:

    }
    

    相反,您想在堆上创建它:

    Request * func()
    {
        Request * r;
        LoginRequest* l = new LoginRequest();
        r = l;
        std::cout<< typeid(*r).name() <<std::endl;  //print the type of OBJECT
        return r; 
    }
    

    也使用智能指针而不是原始指针。

    【讨论】:

      猜你喜欢
      • 2012-08-08
      • 1970-01-01
      • 2014-03-30
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多