#include #include #include //Discuss creating an instance that cannot be copied //We could use pointersbut who is responsible for the destruction? //We can use smart pointer //A silly unmovable class from example 2 class Class1 { private: std::vector a; public: Class1() = default; //default constructor Class1(int a_): a({a_}) {}; //our not so reasonable constructor ~Class1() = default; //default destructor Class1(Class1&&) = default; //move constructor Class1& operator=(Class1&&) = default; //move assignment //this by default deletes copy constructor and copy assignment operator int() const {return a.size();}; //a silly default conversion }; //We want want a function that creates Class1 instance //no problem - move semantics can handle it Class1 my_class1_factory() { return Class1(11); } //std::unique_ptr //It is hard to mess up, even for classes that allow copying std::unique_ptr> my_class1_factory2() { return std::make_unique>(10); //vector of length 10 } //While this pointer guarantees objects existance you use ordinary pointers. //There is one more pointer - it counts its copies std::shared_ptr> my_class1_factory3() { return std::make_shared>(8); //vector of length 8 } //To be used when you would otherwise rely on garbage collection (e.g. immutable data structures) int main() { auto a1 = my_class1_factory(); auto a2 = my_class1_factory2(); std::shared_ptr> a4; { auto a3 = my_class1_factory3(); a4 = a3; } //a3 destroyed, a4 still exists std::cout<size()<<" "<size()<<"\n"; return 0; }