Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing object unique_ptr is pointing to

Really simple question:

I'm kinda new to smart pointers in C++. I think I got the ownership stuff, but I have no idea how to access what they're actually pointing to. When I try to use the member functions/variables of the object I just get the functions of the unique_ptr class, which is not what I want.

like image 593
string_loginUsername Avatar asked Dec 13 '22 21:12

string_loginUsername


1 Answers

I can see three ways of doing that: operator->, operator*, get().

Here is a running code example: ideone it

#include <iostream>
#include <memory>

struct Foo
{
    Foo(std::string v) : value(v) {}
    void Bar() { std::cout << "Hello, " << value << "!" << std::endl; }
    std::string value;
};

int main() {

    std::unique_ptr<Foo> FooPtr = std::make_unique<Foo>("World");

    FooPtr->Bar();
    FooPtr.get()->Bar();
    (*FooPtr).Bar();

    return 0;
}
like image 161
cmourglia Avatar answered Dec 31 '22 17:12

cmourglia