Invoke copy constructor in assignment statement

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
+4
4

. , , eSource, , .

:

Example &operator= (const Example &eSource)
{
    pValue = eSource.pValue;
    return *this;
}

operator=, , , . , , , -.

[Alf return void, ++ . , , - pValue eSource.pValue. , : .]

+3

operator= , ( ) , . *this - .

:

Example& operator= (Example eSource)
{
  swap(eSource);
  return *this;
}

, . , -, , *this.

, operator= ; . , , CopyAssignable MoveAssignable (++ 11 [moveassignable] [copyassignable]); .

, swap() :

void swap(Example &other)
{
  using std::swap;
  swap(pValue, other.pValue);
}

( @JamesKanze ), operator=.

, , ; . ( , ).

+12

, operator= ; . - :

Example& Example::operator=( Example const& other )
{
    Example tmp( other );
    swap( tmp );
    return *this;
}

- swap, , .

. *this.

+2

, operator=() :

Example& operator=(const Example& eSource)
{
    pValue = eSource.pValue;
    return *this;
}

, tmp, .

-, . , , .

-, : ?

+2

Source: https://habr.com/ru/post/1533705/


All Articles