gpt4 book ai didi

c++ - 琐碎的分配器感知容器?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:15:18 24 4
gpt4 key购买 nike

我正在研究/玩分配器,试图了解它是如何工作的。但是我在尝试实现接受分配器的普通容器时遇到了问题。现在我结束了这个:

template<class T, class Allocator =std::allocator<T>> class Container {
public:
using allocator_type = Allocator;
using value_type = T;
using pointer = typename std::allocator_traits<allocator_type>::pointer;
using reference = value_type&;
using size_type = std::size_t;

Container( size_type n =0 , const allocator_type& allocator =allocator_type() ){
std::cout << "ctor" << std::endl;
allocator.allocate(n);
};
};

int main(int argc, const char* argv[]){
Container<int> c {5};
return 0;
}

它给我一个错误 member function 'allocate' not viable: 'this' argument has type 'const allocator_type' (aka 'const std::__1::allocator<int>'), but function is not marked const

请问如何解决这个错误?我错过了什么吗?我打算稍后使用特征,但想先使用旧方法使其工作。

最佳答案

你的线路

allocator.allocate(n);

尝试调用 allocatorallocate 方法,该方法未定义为 const 方法。不过,如果您看一下,allocator 的类型是 const allocator_type&,即 allocator_type 的 const 引用。

那你怎么用呢?您通常可以对 const 对象(或对 const 对象的引用)做的一件事是从它构造一个不同的非常量对象。例如,这构建:

allocator_type(allocator).allocate(n);

正如 SergeyA 在评论中正确指出的那样,不构建临时的临时 allocator_type 而是创建这样一个成员是相当普遍的:

    allocator_type m_alloc; // Should probably be private

Container( size_type n =0 , const allocator_type& allocator =allocator_type() ) :
m_alloc{allocator}{
std::cout << "ctor" << std::endl;
m_alloc.allocate(n);
};

关于c++ - 琐碎的分配器感知容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39374575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com