In an existing class of the project I'm working on, I came across some strange piece of code: the assignment operator calls the copy constructor.
I added the code and now the assignment operator is causing problems. It works fine, though, if I just use the assignment operator generated by the compiler. So I found a solution, but I'm still interested to know why this is not working.
Since the source code is thousands of lines, I created a simpler example to view.
#include <iostream>
#include <vector>
class Example {
private:
int pValue;
public:
Example(int iValue=0)
{
pValue = iValue;
}
Example(const Example &eSource)
{
pValue = eSource.pValue;
}
Example operator= (const Example &eSource)
{
Example tmp(eSource);
return tmp;
}
int getValue()
{
return pValue;
}
};
int main ()
{
std::vector<Example> myvector;
for (int i=1; i<=8; i++) myvector.push_back(Example(i));
std::cout << "myvector contains:";
for (unsigned i=0; i<myvector.size(); ++i)
std::cout << ' ' << myvector[i].getValue();
std::cout << '\n';
myvector.erase (myvector.begin(),myvector.begin()+3);
std::cout << "myvector contains:";
for (unsigned i=0; i<myvector.size(); ++i)
std::cout << ' ' << myvector[i].getValue();
std::cout << '\n';
return 0;
}
Output signal
myvector contains: 1 2 3 4 5
but it should be (in fact, if I just use the assignment operator created by the compiler)
myvector contains: 4 5 6 7 8