简体   繁体   中英

C++ class copy constructor

I am having erratic issue with my copy constructor.

I have a class MyData as follows:

class MyData
{
    private:
    std::vector<double> wavelength;
    std::vector<double> amplitude;

    public:
    MyData::MyData(void) {}

    MyData::MyData(const MyData &cSource)
      : wavelength(cSource.wavelength), amplitude(cSource.amplitude)
    {}
}

In my main program, I am inserting MyData objects into a ring buffer. This is how I am reading it back in main:

MyData data;
data = removeq(&q);

The problem is that sometimes the copied data is missing some values. Etc. if the original size of wavelength is 1, the copied data shows 0. I have debugged my program and the data in the ring buffer is correct etc it shows the correct size of 1.

Anyone have any idea if my copy constructor is wrong or do i need an assignment operator overload ??

Thanks!

The code i used for insert/remove into ring buffer:

void insertq(struct queue *p, MyData v)
{
    int t;
    t = (p->rear+1)%MAX;
    if(t == p->front)
    {   }
    else
    {
            p->rear = t;        
            p->arr[p->rear] = v;
    }
}
MyData removeq(struct queue *p)
{
    MyData empty;   

    if(isempty(p))
    {               
        return empty;
    }
    else
    {       
        p->front = (p->front + 1)%MAX;
        empty = p->arr[p->front];
        return empty;
    }
 }

In order to call the copy constructor you have to declare and initialize your object (using another object) in the same line. Your current code actually calls the overloaded = operator.

A copy constructor is called when you create a new object from an existing object. Here, you are calling the assignment operator:

MyData data;
data = removeq(&q);

If you had used

 Data oldDataObject;
 Data newDataObject = oldDataObject; 

the copy constructor will get invoked.

In the context of your code, you should override the '=' operator to solve this.

MyData& operator = (const MyData& data);

Thanks all for the advice. I have removed the copy constructor and assignment overload methods as suggested.

The issue was with the circular buffer structure I used. I changed the circular buffer code to this example here:

http://www.codeproject.com/Articles/43510/Lock-Free-Single-Producer-Single-Consumer-Circular

and it worked. There seem to be no more errors. I had initially thought that the problem was due to the copy or assignment operator as the error was intermittent and so I did not check if it was the circular buffer that was causing the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM