-1

I am trying to get an object inside of a hash_map by reference. It seems simple enough, but I cannot figure out why it doesn't compile. The error is no match for operator=. In my mind, I am setting the value of fooptr to the address of the found Foo object in the map.

void FooManager::GetFoo(Foo *fooptr, std::string name){
    std::hash_map<std::string, Foo>::iterator it = this->foos.find(name);
    if(it != this->foos.end()){
       *fooptr = &it->second;
    }
}

Foo *foo = 0;
GetFoo(foo, "test");

2 Answers2

3

After reading the comments in john's answer I think I understand your problem. Call by pointer is also call by value. You copy the pointer address. You can call by reference to pointer:

void FooManager::GetFoo(Foo *&fooptr, std::string name){
    std::hash_map<std::string, Foo>::iterator it = this->foos.find(name);
    if(it != this->foos.end()){
       fooptr = &it->second;
    }
}

Foo *foo = 0;
GetFoo(foo, "test");

Now fooptr is a reference to a pointer. When you change the address (value) of fooptr, you also change the address (value) of foo.

Thomas Sablik
  • 16,127
  • 7
  • 34
  • 62
1

You're confused about pointers.

*fooptr = it->second;

Foo foo;
GetFoo(&foo, "test");

Declare an object, pass a pointer to that object, dereference the pointer inside the function.

EDIT

Based on feed back below, the answer should be

*fooptr = &it->second;

Foo* foo = 0;
GetFoo(&foo, "test");

Declare a pointer, pass a pointer to that pointer to the function (a double pointer), dereference the double pointer (to get a pointer) and assign to that a pointer to the map element.

This code is horrendous.

-2 is nothing, i wouldn't worry.

john
  • 85,011
  • 4
  • 57
  • 81
  • I feel like I've tried this, it was my original route. It worked but it didn't seem to be obtaining the actual object - more like it was obtaining a copy of it. I'll try again.. – peer_2_peer_2 Mar 11 '19 at 16:15
  • 1
    @peer_2_peer_2 Of course it's obtaining a copy. Sounds like you need a double pointer. – john Mar 11 '19 at 16:16
  • I guess I just don't get it? I have an object living inside a map. That object has an address. So why does declaring a pointer, and then passing it to a function, and then setting the value of that pointer to the address of the object, not work? – peer_2_peer_2 Mar 11 '19 at 16:18
  • 1
    to use `Foo * FooManager::GetFoo(std::string name)` is must more practical to get a pointer to, of course return nullptr if not found – bruno Mar 11 '19 at 16:19
  • 2
    Because the pointer in your function is only a copy of the pointer outside your function. If you want to change a pointer, you need to pass a pointer to the pointer, same as if you want to change an integer you need to pass a pointer to the integer. (references work as well). – john Mar 11 '19 at 16:20
  • Or do what bruno suggests which is equivalent but a little easier to understand. – john Mar 11 '19 at 16:20