C ++ object not getting std :: move?

I got the following code: ( Live code: C ++ shell )

class Worker
{
public:
  Worker (std::string name):_name (name) {};

  Worker (const Worker & worker):_name (worker._name)
  {  std::cout << _name << " got copied!" << std::endl; }

  Worker (Worker && other):_name (other._name)
  {  std::cout << _name << " got moved!" << std::endl;  }

  ~Worker ()
  {  std::cout << _name << " got destroyed!" << std::endl;  }

  void changeName(std::string name)
  {  this->_name = name;  }

private:
  std::string _name;
};

class Factory
{
public:
  Factory ()
  {  std::cout << "Factory got created!" << std::endl;  }

   ~Factory ()
  {  std::cout << "Factory got destroyed!" << std::endl;  }

  void addWorker (Worker & worker)
  {  this->workers.push_back (std::move (worker));  }

  Worker & getLastWorker ()
  {  this->workers.back ();  }

private:
  std::vector < Worker > workers;
};
int main ()
{
  auto factory = std::make_unique < Factory > ();
  Worker w1 ("Bob");
  factory->addWorker (w1);
  Worker & workerRef = factory->getLastWorker ();
  //workerRef.changeName("Mary");

  return 0;
}

Where I have Factorysaving on my own Workersin vector. When I run main(), I get the following output:

Factory got created!
Bob got moved!
Bob got destroyed!
Factory got destroyed!
Bob got destroyed!

But I can’t understand why it Bob got destroyed!appears twice, since I thought it was Worker w1moving into a vector Workersin Factory. Also, if you comment in workerRef.changeName("Mary");, the code will work with Segmentation fault.

I have been coding with C ++ for a month and am really scared here. I've been looking for a googled game for a long time, but can't find any clues, so any help is great!

+4
source share
4 answers

( , ). , , .

:

  • Worker w1 ("Bob");
  • this->workers.push_back (std::move (worker));

( , ), . , ( w1 main).

+6

: main .

"" , - , (std::move - ).
, - , , " " , .

"move-y" move constructor, :_name (std::move(other._name)), w1 .

, return getLastWorker.
.

+4

:

.

move constractor ( ) , .

, ...

0
source

First of all, your move constructor doesn't move anything, it just copies the line.

And when you insert Workerinto the vector, you still have two objects Worker: one in the function mainand one inside the vector. Both of these objects must be destroyed.

0
source

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


All Articles