DEV Community

dinhluanbmt
dinhluanbmt

Posted on • Edited on

C++ Assignment operator vs _BLOCK_TYPE_IS_VALID

I have been using C++ for a long time, but I didn't pay much attention to the assignment operator and copy constructor until I encountered the "_BLOCK_TYPE_IS_VALID" error.
It took me several hours of googling to figure out the reason.
with this code:

class A {
    int* val;
public:
    A(int v) {
        val = new int(v);
    }
    ~A() {
        delete val;
    };
    A test() {
        A a(2);
        A b(3);
        a = b;// assignment operator
        return a;
    }
Enter fullscreen mode Exit fullscreen mode

we got the "_BLOCK_TYPE_IS_VALID" because when the class does not contain any pointers, the default assignment provided by Compiler is sufficient even it just performs a shadow copy.
but dealing with classes that contain pointers we can get _BLOCK_TYPE_IS_VALID(pHead->nBlockUse).
This error often occurs in Visual Studio when memory corruption or invalid memory access is encountered.
Similarly, in a Linux environment, you may encounter dump values or other exceptions.

so do not forget to define our own assignment operator.

class A{
int* val;
public:
  A(int v){
   val = new int(v);
 }
// assignment operator
 A& operator=(const A& obj){
   *val = *obj.val;
 }
~A(){ delete val;)
};
A test(){
 A a(2);
 A b(3);
 a = b;// assignment operator called
 return a; // copy constructor ??
}
Enter fullscreen mode Exit fullscreen mode

but still we got error?. because the return a; make a copy of a before return.
so we also need our own copy constructor
and this code will work without error:

class A{
int* val;
public:
  A(int v){
   val = new int(v);
 }
// assignment operator
 A& operator=(const A& obj){
   *val = *obj.val;
 }
//copy constructor
A(const A& obj){
 if(val) delete val;
 val = new int(*obj.val);
}
~A(){ delete val;)
};
A test(){
 A a(2);
 A b(3);
 a = b;// assignment operator called
 return a; // copy constructor ??
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)