const correctness and vector

This topic is 4852 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Ok I have a simple method that adds a Node* to a vector<Node*>.
void Node::addDependantRes(const Node* res)
{
dependants.push_back(res);
}


This gives me an error. My understanding of const Node* res is that the object being pointed to cannot be modified through res, which it isnt, unless push_back() works way different than I think. Any help? Also, making a method const means that no changes will occur to *this? Thanks.

Share on other sites
can you post the error?

Share on other sites
the vector would need to be
std::vector<const Node *> dependants;

pretty much the same reason you can't do:

const Node *pF = new Node;
Node *pF2 = pF;

unless pF2 was const as well, or pF is not const.

Share on other sites
Quote:
 Original post by AcidInjuryOk I have a simple method that adds a Node* to a vector.*** Source Snippet Removed ***This gives me an error. My understanding of const Node* res is that the object being pointed to cannot be modified through res, which it isnt, unless push_back() works way different than I think.

You attempt to store it in a vector<Node*>, which means that you will be retrieving non-const pointers to it, and it can be modified through them. As was pointed out, you need a vector<const Node*> (or take a non-const pointer).

Quote:
 Also, making a method const means that no changes will occur to *this?

Yes. (Except for members marked mutable.)

1. 1
2. 2
3. 3
4. 4
Rutin
18
5. 5

• 11
• 21
• 12
• 12
• 11
• Forum Statistics

• Total Topics
631406
• Total Posts
2999894
×