Why is a vector of pointers not castable to a const vector of const pointers?

后端 未结 4 2043
梦谈多话
梦谈多话 2021-01-03 22:17

The type vector is not convertible to const vector. For example, the following gives a compilation error:

4条回答
  •  北海茫月
    2021-01-03 22:44

    As the FQA suggests, this is a fundamental flaw in C++.

    It appears that you can do what you want by some explicit casting:

    vector vc = vector(); 
    vector* vcc = reinterpret_cast*>(&vc);
    fn(*vcc);
    

    This invokes Undefined Behavior and is not guaranteed to work; however, I am almost certain it will work in gcc with strict aliasing turned off (-fno-strict-aliasing). In any case, this can only work as a temporary hack; you should just copy the vector to do what you want in a guaranteed manner.

    std::copy(vc.begin(), vc.end(), std::back_inserter(vcc));
    

    This is OK also from the performance perspective, because fn copies its parameter when it's called.

提交回复
热议问题