gpt4 book ai didi

c++ - C中分配器的错误

转载 作者:行者123 更新时间:2023-12-02 10:30:56 25 4
gpt4 key购买 nike

namespace Test
{
template <typename DataType, typename Allocator = std::allocator<DataType>>
class List
{
private:
struct Node
{
Node* next;
DataType Data;
Node(DataType Data,Node* next = nullptr);
};

typename Allocator::template rebind<Node*>::other allocator;
Node* head;
int size;

public :
List();
~List();

void PushFront(DataType Data);
//void Insert(DataType Data, size_t index);
//void DeleteByIndex(size_t index);

template <typename DataType, typename Allocator = std::allocator<DataType>>
friend std::ostream& operator<<(std::ostream& out, Test::List<DataType, Allocator> list);
};

template<typename DataType, typename Allocator = std::allocator<DataType>>
std::ostream& operator<<(std::ostream& out, Test::List<DataType, Allocator> list)
{
typename decltype(list)::Node* current = list.head;
for (size_t i = 0; i < list.size; ++i)
{
out << current.Data << " ";
current = current->next;
}
}
template<typename DataType, typename Allocator>
inline List<DataType, Allocator>::Node::Node(DataType Data,Node* next) :
Data(Data),
next(next)
{}

template <typename DataType, typename Allocator>
Test::List<DataType, Allocator>::List() :
head(nullptr),
size(NO_SIZE)
{}

template <typename DataType, typename Allocator>
Test::List<DataType, Allocator>::~List()
{
Node* help = head->next;
for (size_t i = 0; i < size; ++i)
{
allocator.destroy(head);
allocator.deallocate(head, 1);
head = help;
help = help->next;
}
}

template <typename DataType, typename Allocator>
void Test::List<DataType, Allocator>::PushFront(DataType Data)
{
Node* newHead = allocator.allocate(1);
allocator.construct(newHead, Data, head);
head = newHead;
}

我主要是想做这个 list
int main()
{
Test::List<int> l;
l.PushFront(10);
l.PushFront(20);
}

我得到错误:

C2664“无效的std::allocator <_Other>::deallocate(_Ty * const,const size_t)”:impossuble将该字符串的“_Ty * const”中的“Test::List>::Node *”的第一个参数转换为字符串( allocator.deallocate(head,1);)

C2440初始化:无法在此字符串的“Test::List>::Node”中转换“_Ty *”(Node newHead = allocator.allocate(1);)

如何解决这个问题(错误由我翻译,如果有错误,对不起)

最佳答案

尝试改变

typename Allocator::template rebind<Node*>::other allocator;


typename Allocator::template rebind<Node>::other allocator;

指针是隐式的。

另外,您应该将 std::allocator_traits与分配器一起使用,而不是直接使用分配器的typedef和函数。

关于c++ - C中分配器的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62304836/

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