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 ();
return 0;
}
Where I have Factory
saving on my own Workers
in 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 w1
moving into a vector Workers
in 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!
source
share