gpt4 book ai didi

c++ - 使用 clang++ v4 和 gcc 6.3 库的自定义分配器

转载 作者:行者123 更新时间:2023-11-30 03:31:48 27 4
gpt4 key购买 nike

在库随 gcc 6.3.1 一起提供的系统 (arch linux) 上,我在使用带有 clang++ 4.0.0 的自定义分配器时遇到了很多麻烦。这是一个最小的非工作示例:

#include <string>

struct myalloc : std::allocator<char> {
using std::allocator<char>::allocator;
};

struct mystring
: std::basic_string<char, std::char_traits<char>, myalloc> {
using std::basic_string<char, std::char_traits<char>, myalloc>::basic_string;
};

int
main()
{
mystring r = "hello";
mystring s (std::move(r));
}

我的意图显然是让 myalloc 成为一个自定义分配器,其行为与系统 std::allocatormystringstd::string 相同,只是它使用 myalloc。这应该是最不可能引起问题的情况。 (很明显,一旦这开始工作,我想进一步自定义分配器。)

代码使用 g++ -std=c++14 -Wall -Werror 编译干净,但是 clang++ -std=c++14 失败:

In file included from strerror.cc:1:
In file included from /usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/6.3.1/../../../../include/c++/6.3.1/string:52:
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/6.3.1/../../../../include/c++/6.3.1/bits/basic_string.h:477:9: error:
no matching constructor for initialization of
'std::__cxx11::basic_string<char, std::char_traits<char>,
myalloc>::_Alloc_hider'
: _M_dataplus(_M_local_data(), std::move(__str._M_get_allocator()))
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
strerror.cc:7:8: note: in instantiation of member function
'std::__cxx11::basic_string<char, std::char_traits<char>,
myalloc>::basic_string' requested here
struct mystring
^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/6.3.1/../../../../include/c++/6.3.1/bits/basic_string.h:109:2: note:
candidate constructor not viable: no known conversion from 'typename
std::remove_reference<allocator<char> &>::type' (aka
'std::allocator<char>') to 'const myalloc' for 2nd argument
_Alloc_hider(pointer __dat, const _Alloc& __a = _Alloc())
^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/6.3.1/../../../../include/c++/6.3.1/bits/basic_string.h:107:14: note:
candidate constructor (the implicit move constructor) not viable: requires
1 argument, but 2 were provided
struct _Alloc_hider : allocator_type // TODO check __is_final
^
/usr/bin/../lib64/gcc/x86_64-pc-linux-gnu/6.3.1/../../../../include/c++/6.3.1/bits/basic_string.h:107:14: note:
candidate constructor (the implicit copy constructor) not viable: requires
1 argument, but 2 were provided
1 error generated.

这只是 clang 或 gcc 库中的错误,还是我的代码在概念上有问题?

最佳答案

最小示例的最小修复是将此成员添加到 struct myalloc

template<class> struct rebind {
using other = myalloc;
};

当然最好不要从 std::allocator 继承(在那种情况下你不需要重新绑定(bind)),也不要从 string 继承,这些类不打算作为公共(public)基础。

关于c++ - 使用 clang++ v4 和 gcc 6.3 库的自定义分配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43924193/

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