lundi 28 juin 2021

How to pass smart pointer instead of "this" in C++ 11?

I am using C++ 11 compiler. I have two classes - class Test and class TestHelper. The class Test is a friend-to-class TestHelper. The class Test is only which we can access from outside. Now, we want to call Test API i.e. setVal(). This setVal() should call Test2 API i.e. setX and is expecting this pointer. I don't want to use this pointer but want to use a smart pointer instead. How can I do so? The notion of this kind of desirability is because of the fact that in reality, my class Test is pretty big. So, I am trying to make a helper class for Test i.e.

class TestHelper;

class Test
{
    friend class TestHelper;
    int x;
public:
    void display() {
        std::cout << x;
     }
    void setVal(int val) {
        TestHelper testH;
        testH.setX(this, 324);
    }
};

class TestHelper
{
public:
    void setX(Test *test, int val) {
        /** some algorithm here and then  change val to something else */
        test->x = val*100;
    }
};

int main()
{
    std::cout << "Hello World!\n";
    Test x;
    x.setVal(130);
}

I tried changing the prototype from void setX(Test *test, int val) to void setX( std::shared_ptr test, int val) but don't know how to pass this pointer as std::shared_ptr test here.

Aucun commentaire:

Enregistrer un commentaire