STL container assignment and const pointers

前端 未结 8 1797
时光取名叫无心
时光取名叫无心 2020-12-29 11:52

This compiles:

int* p1;
const int* p2;
p2 = p1;

This does not:

vector v1;
vector v2;
v2 = v1;         


        
8条回答
  •  暖寄归人
    2020-12-29 12:30

    An important point not mentioned in any of the previous answers is that template specializations make this impossible to implement on a language-wide bases. Consider:

    template
    class Test
    {
        T t;
    };
    
    template<>
    class Test
    {
        char array[1000];
    };
    

    Thus Test contains an array of chars, whereas Test contains a single int.

    #include 
    using namespace std;
    
    int main()
    {
        Test t1;
        Test t2;
        cout << sizeof(t1) << endl; // gives 4
        cout << sizeof(t2) << endl; // gives 1000
        return 0;
    }
    

    In reality vector and vector may hardly differ at all --- in particular, they may have the same size. However, the possibility of explicit template specialization means that they could differ spectacularly, hence the reluctance of the compiler to allow conversion.

    (This answer is mostly copied from http://bytes.com/topic/c/answers/449611-cast-vector-foo-vector-const-foo#post1717570)

提交回复
热议问题