首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >std::scoped_allocator_adaptor和使用std::allocator_arg_t构造函数的类

std::scoped_allocator_adaptor和使用std::allocator_arg_t构造函数的类
EN

Stack Overflow用户
提问于 2016-01-15 11:34:43
回答 2查看 468关注 0票数 5

我在这里找到了一些词,adaptor/construct

如果std::uses_allocator<T, inner_allocator_type>::value==true (类型T使用分配器,例如它是一个容器) 如果std::is_constructible<T, std::allocator_arg_t, inner_allocator_type, Args...>::value==true, 然后打电话 std::allocator_traits::construct(最外层(*this),p,std::allocator_arg,inner_allocator(),前进(Args)..。);

所以,我做了一个简单的测试

代码语言:javascript
复制
struct use_arg {
    template <typename Alloc>
    use_arg(std::allocator_arg_t, Alloc &, int i)
        { std::cout << i << " in use_arg()\n"; }
};

namespace std {

template <typename A> struct uses_allocator<use_arg, A>: true_type {};

} // namespace std

void test_scoped()
{
    std::scoped_allocator_adaptor<std::allocator<use_arg>> sa;
    auto p = sa.allocate(1);
    sa.construct(p, 4);
    sa.destroy(p);
    sa.deallocate(p, 1);
}

但是gcc和clang给了我这些错误https://gist.github.com/anonymous/3e72754a7615162280fb

我还编写了use_a来代替use_arg。它可以成功运行。

代码语言:javascript
复制
struct use_a {
    template <typename Alloc>
    use_a(int i, Alloc &) { std::cout << i << " in use_a()\n"; }
};

是什么使这些行为发生的?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-15 14:45:34

我认为libstdc++和libc++都在做OP示例所需的标准工作。

uses_allocator<use_arg, allocator<use_arg>>是真,但is_constructible<use_arg, allocator_arg_t, inner_allocator_type, int>是假的,因为use_arg不能从rvalue分配器构造,所以construct调用应该格式错误。

然而,我认为这是标准的一个缺陷。考虑这种类型:

代码语言:javascript
复制
struct use_arg {
  using allocator_type = std::allocator<use_arg>;
  use_arg(allocator_type&&) { }
};

uses_allocatoris_constructible特性都是正确的,但是对scoped_allocator_adaptor::construct(pointer)的调用将无法编译。

检查is_constructible<T, inner_allocator_type> (从rvalue分配器测试构造),然后通过inner_allocator_type& (这是一个lvalue)是不一致的,但标准是这么说的。

票数 3
EN

Stack Overflow用户

发布于 2016-01-15 12:07:44

问题是,您通过引用接收Alloc

代码语言:javascript
复制
std::is_constructible<T, std::allocator_arg_t, inner_allocator_type, Args...>::value==true

在您的示例中,inner_allocator只是std::scoped_allocator_adaptor<std::allocator<use_arg>>,不能转换为std::scoped_allocator_adaptor<std::allocator<use_arg>>&。您只需按值或通过Alloc接收const-reference即可。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34810168

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档