tags:

views:

67

answers:

2

I have a class with a map<K,V> variable which gets its value in the c'tor like so:

class Foo {
    map<K,V> m;
    Foo (map<K,V>& newM) : m(newM) {}
    map<K,V>::iterator bar () { ... }
}

the function bar iterates through the map m, and return some an iterator to some element. I'm calling the function like this:

std::map<K,V> map;
//fill map
Foo foo(map);
map<K,V>::iterator it = foo.bar();

my question is, at this moment, does it point to a member of map? or was it copied to Foo.m and therefor the iterator points to a different map?

A: 

The iterator will point to the map contains in your class Foo. Surely that shouldn't be an issue though as you've copied the map to the class?

What I mean by that is, I assume you will do something like this:

map<K,V> original;
Foo foo(original);
map<K,V>::iterator it = foo.begin(), itEnd = foo.end();
for (; it != itEnd; ++it)
{
  // Do something with *it
}
Mark Ingram
Ownership has not been transferred - a copy has been made.
anon
Thanks, have updated the text.
Mark Ingram
+2  A: 

It will point to the new map, as you copied the map into variable m in the ctor of the class. The statement m(newM) in the initialization list invokes the copy constructor of the std::map class and copies individual elements of the passed map into the destintation map m. Hence when you invoke bar method, it will return the iterator from this new map.

EDIT Example code for storing the std::map as reference:

class Foo {
public:
    map<int,int>& m; //Note: the change here, I am storing a reference
    Foo (map<int,int>& newM) : m(newM) {}
    map<int,int>::iterator bar () { return m.begin();}
};


int main()
{
    std::map<int,int> map1;
    Foo foo(map1);
    map<int,int>::iterator it = foo.bar();

    if(it == map1.begin())
    {
        std::cout<<"Iterators are equal\n";
    }
}
Naveen
+1. To add: if that was intended, the Foo constructor should accept a const reference.
peterchen
@Naveen is it possible to somehow make it return a pointer to the original map - using reference and not pointers?
Amir Rachum
@Amir Rachum: Yes, you can return iterator to original container if you store only a reference in your class. But note that it is *risky* as you have to make sure that your original map doesn't go out of scope until `foo` object is destroyed. Otherwise, you will end up in having an invalid reference and your code will behave unpredictably.
Naveen
@Naveen can you show a quick example of the syntax? I'm a little confused with references.
Amir Rachum
@Amir Rachum : Edited post to add an example code.
Naveen
@Naveen thanks!
Amir Rachum