V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
wohenfuyou
V2EX  ›  问与答

c++指针的问题,我有点晕

  •  
  •   wohenfuyou · 2021 年 1 月 20 日 · 1401 次点击
    这是一个创建于 1819 天前的主题,其中的信息可能已经有所发展或是发生改变。

    PowerGridModel::GridModelArea* readMessageFile()
    {

    //只看这部分就行了,返回的是 protobuf 类的指针<br>
    PowerGridModel::GridModelArea* area_rec = gridModelResponse.mutable_divinfo(4);<br>
    
    cout << area_rec->id().id1() << endl;<br>
    cout << area_rec->name() << endl;<br>
    cout << area_rec->level() << endl;<br>
    
    return area_rec;<br>
    

    }
    int main()
    {
    PowerGridModel::GridModelArea* rec = readMessageFile(); cout << rec->id().id1() << endl; cout << rec->name() << endl; cout << rec->level() << endl; }

    打印信息:
    101
    辽宁沈阳
    1005
    101

    1005

    中间的 name 第二次打印为什么打不出来呢,是我指针用的有问题,还是 protobuf 类有问题?

    QBugHunter
        1
    QBugHunter  
       2021 年 1 月 20 日
    能写出这种代码的人也是人此。。。
    wohenfuyou
        2
    wohenfuyou  
    OP
       2021 年 1 月 20 日
    @QBugHunter 好久没写 c++了,指针方面都忘记怎么传了
    wutiantong
        3
    wutiantong  
       2021 年 1 月 20 日
    save an object, not a pointer
    wohenfuyou
        4
    wohenfuyou  
    OP
       2021 年 1 月 20 日
    @wutiantong 可以展开说一下么~
    wutiantong
        5
    wutiantong  
       2021 年 1 月 20 日
    @wohenfuyou 返回裸指针的函数无法延续对象的生命周期,指针传出来了但对象死掉了。
    ysc3839
        6
    ysc3839  
       2021 年 1 月 20 日
    gridModelResponse 是哪来的呢?请给出完整代码。
    labubu
        7
    labubu  
       2021 年 1 月 21 日
    你这掐头去尾的代码我更晕了
    wohenfuyou
        8
    wohenfuyou  
    OP
       2021 年 1 月 21 日
    @ysc3839 gridModelResponse 是局部的 解决了 谢谢
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   3980 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 05:15 · PVG 13:15 · LAX 21:15 · JFK 00:15
    ♥ Do have faith in what you're doing.