I am trying to insert a reference to my object, but i am getting large number of errors. What do i need to modify in the custom object, so that it can be inserted successfully?
The code is shown below:
#include <map>
#include <iostream>
#include <string>
using namespace std;
class A
{
public:
A()
{
cout << "default constructor" << endl;
}
A(A & a)
{
cout << "copy constructor" << endl;
}
A & operator=(A & a)
{
cout << "assignment operator" << endl;
return *this;
}
~A()
{
cout << "destructor" << endl;
}
};
int main()
{
map<string, A&> m1;
A a;
m1["a"] = a;
return 0;
}
UPDATE:
It is possible to create a map with reference such as
map<string, A&>The error was in usage of [] operator. By making following change, the code works
typedef map<string, A&> mymap; int main() { mymap m1; A a; cout << &a << endl; m1.insert(make_pair<string, A&>("a", a)); mymap::iterator it = m1.find("a"); A &b = (*it).second; cout << &b << endl; // same memory address as a return 0; }
A(A&a)is not the one you want -- you wantA(A const&), and the same foroperator=. This is unrelated to your problem, which is solved below.