Class with movable object - abhijeetk/chromium-development GitHub Wiki

#include <iostream>
#include <vector>
#include <string>
using namespace std;
class B {
    std::string objName;
public:
    B ( B && );
    B &  operator= ( B && );
    B ( const B & ) = delete;
    B & operator= ( const B & ) = delete;
    B(const std::string & name) :
            objName(name) {}
    virtual ~B() {}
    std::string name() const { return objName;}
};
B::B ( B && ) {
      std::cout << "Move constructor" << std::endl; 
};
B &  B::operator= ( B && ) {
      std::cout << "Move assignment" << std::endl; 
};
    
class A {
public:
   std::vector<B> v;
   void take(const B& b)
   {
       
        std::cout << "Before pushing" << std::endl; 
         #if 0
        v.push_back(std::move(b));
        #endif
        std::cout << "After pushing" << std::endl; 
        
   }
};
int main()
{
   A a;
   B b("I am object of B");
   std::cout << "Before: " << b.name() << std::endl;
   a.take(std::move(b));
   std::cout << "After: " << b.name() << std::endl;
   std::cout << "A has elements: " << std::endl;
   for(B &b : a.v)
      std::cout << "  " << b.name() << std::endl;
      
   const B b1("\n...I am object of B");
   a.take(std::move(b1));
}
⚠️ **GitHub.com Fallback** ⚠️