Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer of class local variable? [duplicate]

Possible Duplicate:
Can a local variable's memory be accessed outside its scope?

Is there worrying thing to do a code such (getIDs() returns a pointer):

class Worker{
private:
    int workerID;
    int departID;
    int supervisorID;
public:
    Worker() 
    {
        workerID=0;
        departID=0;
        supervisorID=0;
        name="anonymous";
        workerAddress="none";
    }

    void setIDs(int worker, int depart, int supervisor)
    {
        workerID=worker;
        departID=depart;
        supervisorID=supervisor;
    }

    int* getIDs()
    {
        int id[3];
        id[0]=workerID;
        id[1]=departID;
        id[2]=supervisorID;
        return id;
    }
};

And then, use it such:

Worker obj;
obj.setIDs(11,22,33);
cout<<(*obj.getIDs())<<endl;
cout<<++(*obj.getIDs())<<endl;
cout<<++(++(*obj.getIDs()))<<endl;

I am wondering about that because the compiler shows:

Warning 1 warning C4172: returning address of local variable or temporary

like image 715
Aan Avatar asked Dec 27 '22 10:12

Aan


1 Answers

Your int id[3] is allocated on a stack and gets destroyed when your int* getIDs() returns.

like image 149
arrowd Avatar answered Jan 13 '23 06:01

arrowd