Reputation: 53
The following code is to verify if I have a pointer member in a class, without making an overloaded assignment operator. When I make two instances equal,it will just make the pointers point to the same thing instead of copying the data. However, I got an error trying to compile before I could verify. It appears to me that it implies a pointer member in class has to be pointed to a heap-allocated data. Is it right?
The error is: initializing pointer member 'a' with the stack address of parameter 'aa' [-Werror,-Wdangling-field]
Second question is when do we need an overloaded "="operator? I guess would be when we have a pointer member in the class and we want whatever the pointer points to to be copied again instead of just making two pointer from the two classes point to same thing. Could somebody tell me this is correct. Thanks!
class ClassA {
int* a;
int* b;
ClassA():a(NULL),b(NULL){};
ClassA(int aa,int bb):a(&aa),b(&bb){};
};
int main(){
ClassA test;
ClassA subject(5,6);
test = subject;
}
Upvotes: 1
Views: 226
Reputation: 63892
No, there's nothing saying that he address contained in a pointer must be the location of an object with dynamic storage duration, but please be careful when initializing them with addresses of variables on the stack (having automatic storage duration).
As your compiler tells you; you are currently assigning the address of two temporaries to the pointers inside your class. This means that after the constructor is finished, and aa
and bb
are no longer alive, but you can still potentially refer to them through this->a
, and this->b
.
If you try to use *(this->a)
and *(this->b)
when their pointed-to-object in no longer available you are invoking undefined behavior, meaning that your application will most likely crash since you are trying to access memory which is no longer valid to use.
operator=
?This is an often asked question on stackoverflow, and I'd recommend you to read through the below questions/answers:
Upvotes: 5
Reputation: 7562
this line doesn't look good:
ClassA (int aa, int bb) : a(&aa), b(&bb) {};
the parameters are plain integers, so they come in by-value, it means their copies exist on the stack as long as the constructor scope goes. then they're gone. your pointers now point to unalocated memory, so dereferencing would lead to a segfault.
as for your second question, please read this thread that gives a beautiful explanation for the assignment operator.
Upvotes: 1