类成员的动态分配和值

问题描述 投票:-1回答:1

为什么第二次调用kcheck(base)值会改变?

class Base{
public:
    int k=0;
    virtual void print(){
        cout<< k<<endl;
    }
};

Base* check(Base* p){
   Base* t = new Base;
   t->k = 4;
   delete p;
   return t;
}

int main(){
    Base* base = new Base;
    cout<< check(base)->k; // first call, print 4
    cout<<"\n";
    cout<<base->k;// print 0
    check(base); // second call
    cout<<"\n";
    cout<< base->k; // print 4
    cout<<"\n";
    return 0;
}

输出:

4
0
4
c++ c++11 dynamic-memory-allocation
1个回答
0
投票
ptrdelete ptr后访问UB指向的存储器

我的猜测是,您调用delete p(又称base)后,Base* t = new Base分配用于指向base指向的内存。

© www.soinside.com 2019 - 2024. All rights reserved.