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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs