Home > database >  Cpp/ C unique Pointer on objects access functions of that class
Cpp/ C unique Pointer on objects access functions of that class

Time:11-30

How do I access functions via a unique pointer pointing on an object of that class

struct foo
{
    foo(int);
    void getY();
};

int main()
{
    foo f1(1);
    f1.getY();
    std::unique_ptr<foo> ptr1 = make_unique<foo>(2);
    *ptr1.getY(); // Error
};

foo has a constructor with an int as argument,getY() just prints out that int value.

Obviously foo f1(1); f1.getY(); works but idk how to access getY() over the pointer. unique_ptr<foo> ptr1 = make_unique<foo>(2); *ptr1.getY(); was my initial idea, but it doesn't work.

CodePudding user response:

You can use it as an ordinary pointer. For example

( *ptr1 ).getY();

or

ptr1->getY();

Or even like:)

p.get()->getY();
( *p.get() ).getY();

That is there are declared the following operators and the accessor in the class template unique_ptr

add_lvalue_reference_t<T> operator*() const;
pointer operator->() const noexcept;
pointer get() const noexcept;

CodePudding user response:

The problem is that due to operator precedence when you wrote *ptr1.getY();, it was equivalent to writing:

*(ptr1.getY());

So this means you're trying to call a member function named getY on the smart pointer ptr1 but since ptr1 has no member function called getY you get the error.

To solve this you should write:

( *ptr1 ).getY();//works now 

This time you're specifically asking/grouping *ptr together and then calling the member function getY on the resulting object . And since the resulting object is of type foo which has a member function getY, this works.

  • Related