Jump to content
  • Advertisement
Sign in to follow this  
AcidInjury

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.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!