简体   繁体   English

在模板类中使用std :: allocator时出错

[英]Error when using the std::allocator in the template class

Trying to figure out how to use std :: allocator. 试图弄清楚如何使用std :: allocator。

#include <iostream>

template <typename T, typename A>
struct vector_base
{
  A       allocator;
  T*      data;
  size_t  size;
  size_t  space;

  vector_base(const A &alloc, size_t n)
    :allocator(alloc), data(alloc.allocate(n)), size(n), space(n)
  {}

  ~vector_base() {allocator.deallocate(data, space);}
};

int main() {
  std::allocator<int> my_allocator;
  vector_base<int, std::allocator<int>> vector(my_allocator, 10);

  return 0;
}

Error: 错误:

error: passing 'const std::allocator' as 'this' argument discards qualifiers [-fpermissive] :allocator(alloc), data(alloc.allocate(n)), size(n), space(n) 错误:将“ const std :: allocator”作为“ this”参数传递会丢弃限定符[-fpermissive]:allocator(alloc),data(alloc.allocate(n)),size(n),space(n)

alloc is a const& , you're trying to call allocate on it which is a non-const method, that's not allowed. alloc是一个const& ,您试图在其上调用allocate ,这是一个非const方法,这是不允许的。

Call allocate on your initialized member instead: 而是在初始化的成员上调用allocate

  vector_base(const A &alloc, size_t n)
    :allocator(alloc), data(allocator.allocate(n)), size(n), space(n)
  {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误“没有从 &#39;std::vector 进行的已知转换<double, std::allocator<double> &gt;&#39; 到 &#39;double *&#39; ” 使用 std::count_if() 时? - Error “ no known conversion from 'std::vector<double, std::allocator<double> >' to 'double *' ” when using std::count_if()? 为什么std :: allocator是模板? - Why is std::allocator a template? 将左值传递给用作临时 std 容器的模板参数的通用引用参数时与分配器相关的错误 - Allocator-related error when passing lvalue to a universal reference parameter that is used as template parameter to a temporary std container 在模板类中使用标准分配器时,模板的声明是什么样的? - What does a declaration of template look like when using the standard allocator in a template class? std :: scoped_allocator_adaptor和一个使用std :: allocator_arg_t的构造函数的类 - std::scoped_allocator_adaptor and a class with a constructor using std::allocator_arg_t 使用 std::allocator 时 std::to_string 返回空字符串 - std::to_string return empty string when using std::allocator 在模板中使用std :: max时出错 - Error when using std::max in template 使用 std::allocator C++ 时字符串和 int 之间的差异 - Difference betwen string and int when using std::allocator C++ 类模板allocator_traits - class template, allocator_traits 模板typedef与std :: vector有自定义分配器 - template typedef with std::vector to have custom allocator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM