开发者

Operator() as a subscript (C++)

开发者 https://www.devze.com 2022-12-24 08:23 出处:网络
I use operator() as a subscript operatorthis way: double CVector::operator() (int i) const { if (i >= 0 && i < this->size)

I use operator() as a subscript operator this way:

double CVector::operator() (int i) const
{
 if (i >= 0 && i < this->size)
  return this->data[i];
 else
  return 0;
}

double& CVector::operator() (int i)
{
 return (this->data[i]);
}

It works when I get values, but I get an error when I try to write assign a value using

a(i) = 1;

UPD: Error text:

Unhandled exception at 0x651cf54a (msvcr100d.dll) in CG.exe: 0xC0000005: Access violation reading locat开发者_运维问答ion 0xccccccc0.


Like I said in my comment, the problem is your flawed design. I make a 100% guarantee on one of two things:

  1. The value you are passing to the assignment function is out of valid range.
  2. The member data is pointing to invalid space in memory.

In either case, I would suggest adding:

#include <cassert>

and adding assert(i >= 0 && i < this->size) instead of the silent failures:

double CVector::operator() (int i) const
{
    assert(i >= 0 && i < this->size);
    return this->data[i];
}

double& CVector::operator() (int i)
{
    assert(i >= 0 && i < this->size);
    return (this->data[i]);
}


That's because you haven't implemented error handling in double& CVector::operator() (int i) like you did for the other function which overloads ().

Change it to:

double& CVector::operator() (int i)
{
 if (i >= 0 && i < this->size)
 {
  return this->data[i];
 }
 else // Whatever manner you want to gracefully exit the program
 {
  std::cout<<"Out of bounds!"<<endl;
  exit(1);
 }
}

You should also consider changing the error handling mechanism in the other function from return 0; to something more meaningful.


Unhandled exception at 0x651cf54a (msvcr100d.dll) in CG.exe: 0xC0000005: Access violation reading location 0xccccccc0.

0xcc is the MSVC uninitialized memory byte value. In other words, your problem is most likely due to accessing an uninitialized pointer or a pointer that was derived from uninitialized memory.


The problem is that you do not check for out-of-range index in your double& version of operator().

You probably cannot guarantee that data[i] points to a valid memory address for a large enough i. You should either check for out-of-range index and throw some exception or resize your vector (by allocating more memory do data) to be able to hold more values.

0

精彩评论

暂无评论...
验证码 换一张
取 消