lllook
lllook

Reputation: 749

error when adding into vector of pointers

class A{
  Add(const B&);
  vector <B*> vect;
};

A & A::Add(const B& obj){
  vect.push_back(&obj);
  return *this;
}

here I am getting fpermissive error, because argument of push_back is constant, how do I get rid of this?

I tried to create local copy in Add such as

B tmp;
tmp = obj;
vect.push_back(&tmp);

but I am not sure about this, as program step out of this method Add, tmp gets destructed, and adress in vector will point to invalid place in memory?

Upvotes: 0

Views: 72

Answers (2)

Triskeldeian
Triskeldeian

Reputation: 628

Your problem is that if you provide a const reference as the function parameter of Add you are telling the compiler that whatever you are passing is never going to be changed as an effect of that function. On the other hand you try to store a non-const pointer in the vector which means that the users of that vector are allowed to change the value correlated to that pointer. To get rid of the error you have to decide what is the type of behaviour you actually want from your program: if you want to store read-only references to your "B" objects then you have to store them as const pointer in the vector. If you want the users of that vector to be able to use non-const functions of B, that is to change B, you have to pass it to the Add function as non-const reference.

Upvotes: 1

SomeWittyUsername
SomeWittyUsername

Reputation: 18348

Your problem arises from API inconsistency. 2 options here:

  • Drop the const from the signature of Add: Add(B&)
  • Store const B* pointers in the vector: vector<const B*> vect;

The first option will allow to modify the contents of your objects while the second one will forbid it. The choice depends on your program logic.

Upvotes: 3

Related Questions