Sign in to follow this  

const correctness and vector

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by AcidInjury
Ok I have a simple method that adds a Node* to a vector<Node*>.

*** 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.)

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this