0
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?

1
  • Are you sure you want to store pointers to objects whose lifetimes you have no idea about? Commented Apr 11, 2015 at 9:02

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

if I use second option, what exactly does vector<const B*> vect; mean ? will it behave as normal vector?
@lllook It means that the vector will store pointers to immutable objects, i.e., you won't be able to modify these objects. It's important to distinguish between the ability to modify the vector by modifying the pointers stored within to the ability to modify the pointed objects. You'll be able to do the former but not the latter.
thanks, this seems to be an effect I was looking for
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.