Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the C++ Object not get std::moved?

Tags:

c++

c++14

move

I got the following code: (Code Live: 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 a Factory storing at its Workers in a vector. When I run the 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 get my head around why Bob got destroyed! appears two times, as I thought Worker w1 gets moved to the vector workers in the Factory. Additionally, if you comment in workerRef.changeName("Mary"); the code crashes with Segmentation fault.

I'm coding with c++ for a month now and really struggle here. I have googled quite for a while, but can't find a hint, so any help is great!

like image 878
DummySenior Avatar asked Dec 11 '22 09:12

DummySenior


1 Answers

Moving only moves the contents of objects (if implemented like that, it could just copy). It doesn't mean the original object vanishes, only that its value possibly changes.

Your example creates two objects in two places:

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

The second steals the guts from the first (on the face of it, anyway), but the first is still alive. And any living object will have its destructor called at the end of its lifetime (for w1 it's the closing of main).

like image 187
StoryTeller - Unslander Monica Avatar answered Dec 12 '22 21:12

StoryTeller - Unslander Monica