Example of Unique_Ptr in C++14 and C++17


using C++14


#include <iostream>
#include <memory>

using namespace std;

class MyObject1 
{
private:
    int data;
    
public:
        MyObject1(){
            
        }
    
        MyObject1(int aNumber){
            data = aNumber;
            
        }
        
    int getData() {return data;}
};

class MyObject2
{
public:
    void doSomething(unique_ptr<MyObject1> ptr)
    {
        cout << "data = " << ptr->getData();
    }
};


int main()
{
    unique_ptr<MyObject1> upObj1( new MyObject1(5) );
    unique_ptr<MyObject2> upObj2( new MyObject2 );

    upObj2->doSomething(std::move(upObj1));
    return 0;
}

using C++17


#include <iostream>
#include <memory>

using namespace std;

class MyObject1 
{
private:
    int data;
    
public:
        MyObject1(){
            
        }
    
        MyObject1(int aNumber){
            data = aNumber;
            
        }
        
    int getData() {return data;}
};

class MyObject2
{
public:
    void doSomething(unique_ptr<MyObject1> ptr)
    {
        cout << "data = " << ptr->getData();
    }
};

int main()
{
    auto upObj1 = make_unique<MyObject1>(5);
    auto upObj2 = make_unique<MyObject2>();
    
    upObj2->doSomething(std::move(upObj1));
    
    return 0;
}



MCQs

About Us | Contact Us | Privacy Policy | Career  | Online Training
Youtube   LinkedIn   Facebook   Twitter   Instagram  
Copyright©CppBuzz.com
Like many websites, we use cookies to ensure best browsing experience on our website. While using this website, you acknowledge to have read and accepted our cookie and privacy policy.