wohenfuyou
V2EX  ›  问与答

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

  •  
  •   wohenfuyou · Jan 20, 2021 · 1546 views
    This topic created in 1945 days ago, the information mentioned may be changed or developed.

    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  
       Jan 20, 2021
    能写出这种代码的人也是人此。。。
    wohenfuyou
        2
    wohenfuyou  
    OP
       Jan 20, 2021
    @QBugHunter 好久没写 c++了,指针方面都忘记怎么传了
    wutiantong
        3
    wutiantong  
       Jan 20, 2021
    save an object, not a pointer
    wohenfuyou
        4
    wohenfuyou  
    OP
       Jan 20, 2021
    @wutiantong 可以展开说一下么~
    wutiantong
        5
    wutiantong  
       Jan 20, 2021
    @wohenfuyou 返回裸指针的函数无法延续对象的生命周期,指针传出来了但对象死掉了。
    ysc3839
        6
    ysc3839  
       Jan 20, 2021
    gridModelResponse 是哪来的呢?请给出完整代码。
    labubu
        7
    labubu  
       Jan 21, 2021
    你这掐头去尾的代码我更晕了
    wohenfuyou
        8
    wohenfuyou  
    OP
       Jan 21, 2021
    @ysc3839 gridModelResponse 是局部的 解决了 谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   957 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 21:41 · PVG 05:41 · LAX 14:41 · JFK 17:41
    ♥ Do have faith in what you're doing.