Hugo
Hugo

Reputation: 337

Why I'm allowed to assign a new address to a vector containing constant pointers?

I think the title is clear on explaining my problem.... consider the following snippet:

class Critter {
    int m_Age;
};

int main()
{
    vector<Critter* const> critters;
    for(int i = 0; i < 10; ++i)
        critters.push_back(new Critter());

    critters[2] = new Critter();

    return 0;
}

Shouldn't the line critters[2] = new Critter(); be illegal?

Thank You

Upvotes: 1

Views: 122

Answers (2)

Hugo
Hugo

Reputation: 337

Sorry, I didn't post the entire code because what's missing are only the includes and using... anyway here is the entire code:

#include <iostream>
#include <vector>

using namespace std;

class Critter {
    int m_Age;
};

int main()
{
    vector<Critter* const> critters;
    for(int i = 0; i < 10; ++i)
        critters.push_back(new Critter());

    critters[2] = new Critter();

    return 0;
}

And this code as it is, compiles fine, even without a warning in VS 2010... Thanks once more...

Upvotes: 0

CB Bailey
CB Bailey

Reputation: 792497

Actually this line should be illegal (even given #include <vector> and using std::vector;):

vector<Critter* const> critters;

Because it is a requirement for a type to be used in a container to be assignable and anything that is const clearly isn't.

Upvotes: 5

Related Questions