Transferring Dynamic Memory between Functions - C++ Data Type

C++ examples for Data Type:shared_ptr

Description

Transferring Dynamic Memory between Functions

Demo Code

#include <iostream>
#include <memory>

using namespace std;

class MyClass/*from  w w  w  .j  a va  2  s  .com*/
{
private:
    int m_Number{ 0 };

public:
    MyClass(int value): m_Number{ value }{
    }
    ~MyClass(){
        cout << "Destroying " << m_Number << endl;
    }

    void operator=(const int value){
        m_Number = value;
    }
    int GetNumber() const{
        return m_Number;
    }
};

using SharedMyClass = shared_ptr< MyClass >;

void ChangeSharedValue(SharedMyClass sharedMyClass)
{
    if (sharedMyClass != nullptr)
    {
        *sharedMyClass = 100;
    }
}

int main(int argc, char* argv[])
{
    SharedMyClass sharedMyClass{ new MyClass(10) };

    ChangeSharedValue(sharedMyClass);

    return 0;
}

Result


Related Tutorials