c – 为什么是非法的:将指针的向量复制到指向常量的指针的向量中

前端之家收集整理的这篇文章主要介绍了c – 为什么是非法的:将指针的向量复制到指向常量的指针的向量中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问题

以下代码不会在C11(也不是C14)中编译.我了解编译器的错误输出,但为什么标准不允许?

//main.cpp

#include <vector>

int main(void)
{
    double a = 3.0;
    double b = 3.0;

    //It works with mere pointers
    const double* ptrToConst = &a;
    /***/ double* ptrToObj   = &a;
//  ptrToObj = ptrToConst; //Illegal : that's understandable…
    ptrToConst = ptrToObj;   //Works

    //But the same doesn't work with vectors to pointers
    std::vector<const double*> ptrsToConst = {&a,&b};
    std::vector</***/ double*> ptrsToObj   = {&a,&b};
//  ptrsToObj = ptrsToConst; //Illegal : that's understandable
    ptrsToConst = ptrsToObj; //Illegal : but why?!
}

错误来自ptrsToConst = ptrsToObj.实际上,似乎不可能复制指针的向量std :: vector< T *>变成一个向量指向常量的std :: vector< const T *>.请注意,在这两种情况下,指针本身不是常量.

为什么这个行为是非法的?
最优雅的工作是什么?

更多细节

如果我通过调用clang –std = c 11 main.cpp进行编译,则会显示以下错误消息:

main.cpp:19:17: error: no viable overloaded '='
    ptrsToConst = ptrsToObj; //Illegal : but why?!
    ~~~~~~~~~~~ ^ ~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/bits/stl_vector.h:436:7: note: candidate
      function not viable: no known conversion from 'vector<double *,allocator<double *>>' to 'const
      vector<const double *,allocator<const double *>>' for 1st argument
      operator=(const vector& __x);
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/bits/stl_vector.h:448:7: note: candidate
      function not viable: no known conversion from 'vector<double *,allocator<double *>>' to 'vector<const
      double *,allocator<const double *>>' for 1st argument
      operator=(vector&& __x) noexcept(_Alloc_traits::_S_nothrow_move())
      ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.4.0/../../../../include/c++/5.4.0/bits/stl_vector.h:470:7: note: candidate
      function not viable: no known conversion from 'std::vector<double *>' to 'initializer_list<value_type>' (aka
      'initializer_list<const double *>') for 1st argument
      operator=(initializer_list<value_type> __l)
      ^
1 error generated.

与gcc(g)一样尝试产生类似的错误消息.

显然,实现向量的方式不允许我正在尝试执行的操作.但是对于正确性来说,这是一个安全的操作呢?

解决方法@H_502_23@
你可以这样做,只是不用operator =.您需要assign成员函数,该函数对每个单独的元素执行转换.
ptrsToConst.assign(ptrsToObj.begin(),ptrsToObj.end());

猜你在找的C&C++相关文章