header file:
private:
vector<int*>* nums;
public slots:
void buttonClicked();
cpp file:
NewWindow(){
int one = 1;
int* pone = &one;
int two = 2;
int* ptwo = &two;
vector<int*> numbers;
numbers.push_back(pone);
numbers.push_back(ptwo);
nums = &numbers;
test();
}
//Prints size of nums vector
void NewWindow::test(){
stringstream woo;
woo << nums->size()<<endl;
cout << woo.str();
}
//I just had one button on my gui
void NewWindow::buttonClicked(){
test();
}
When I run this, the first test method executes in the contructor and outputs 2, as expected. However, after clicking the button (i.e executing buttonClicked() method), the test method outputs a seemingly arbitrary number (e.g. 4292719658). After messing around a bit I discovered that if I make the numbers vector an attribute, the test() method will output 2 each time. Why was I getting a weird output with numbers as a non-attribute?
If
numbersis a local variable, as it is here:then it is destroyed, and ceases to exist, when it goes out of scope. In this case, when the
NewWindowfunction returns. Referencing a non-existent object (as you do through thenumspointer), results in undefined behavior.If
numbersis a member variable, on the other hand, it is destroyed when the object of which it is a member is destroyed.