c++ - 为什么 const 指针的 vector 在 c++17 中工作

标签 c++ c++11 vector

这个问题在这里已经有了答案:





What is the difference between const int*, const int * const, and int const *?

(21 个回答)


2年前关闭。




我看到了 this answer: Does C++11 allow vector<const T> ?解释您应该如何做 不是 使用 const Tstd::vector .我用 std::vector<const int> int_vector 试过这个并得到编译器错误,这是意料之中的。但是如果我创建一个 std::vector<const CustomType*> custom_type_vector我可以毫无问题地使用它。这是否意味着 C++ 允许 const 指针作为 std::vector 中的元素?但不允许 const Tstd::vector ?

最小的可重复示例

std::vector<const int> vec_a; // compiler will complain this.
std::vector<const int*> vec_a; // compiler will accept this.

使用 std::vector<const int> 的错误日志是:
/usr/include/c++/7/ext/new_allocator.h:93:7: error: 'const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const int; __gnu_cxx::new_allocator<_Tp>::const_pointer = const int*; __gnu_cxx::new_allocator<_Tp>::const_reference = const int&]' cannot be overloaded
       address(const_reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
/usr/include/c++/7/ext/new_allocator.h:89:7: error: with '_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const int; __gnu_cxx::new_allocator<_Tp>::pointer = const int*; __gnu_cxx::new_allocator<_Tp>::reference = const int&]'
       address(reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
/usr/include/c++/7/ext/new_allocator.h:125:19: error: invalid conversion from 'const void*' to 'void*' [-fpermissive]
  ::operator delete(__p);
  ~~~~~~~~~~~~~~~~~^~~~~

我的编译器版本是 gcc 版本 7.4.0 (Ubuntu 7.4.0-1ubuntu1~18.04.1)

最佳答案

m_pOatrix correctly points out in the comments , std::vector<const CustomType*>不是 const 指针 vector ,而是指向 const 对象的指针 vector ,这是允许的。

如果您改为使用 const 指针,则不允许这样做:

std::vector<Foo> f; // allowed
std::vector<const Foo> f; // disallowed
std::vector<const Foo*> f;// allowed
std::vector<Foo* const> f; // disallowed

使用 const 的技巧是它适用于紧邻它左侧的事物,或者如果它在开头(就像经常这样),那么它适用于第一件事。
const Foo*; // pointer to const Foo, same as Foo const*
Foo* const; // const pointer to Foo

关于c++ - 为什么 const 指针的 vector 在 c++17 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59003410/

相关文章:

c++ - Boost::Positional Options 无法使所有参数位置化

c++ - 错误在 `./2' : free(): invalid pointer: 0x000000000096044c *** Aborted (core dumped)

c++ - 生产者-消费者实现中的条件变量应该如何初始化

c++ - 数组、对象、类来组织具有多项选择和真/假问题的测试问卷程序

java - 使用java中Vector的indexOf()方法来匹配一个成员变量

c++ - ros出现 'undefined reference to libusb'错误怎么解决?

c++ - 使用自定义提取运算符时出现错误 C2679

c++ - 尝试使用初始化器列表来初始化类的成员值时出现编译错误

c++ - 给 boost vector 分配几个数字

c++ - boost 测试不 init_unit_test_suite