scoped_allocator_adaptor 似乎需要默认构造分配器

问题描述

在我使用 scoped_allocator_adaptor 的实验中,我试图将从 main(..) 获得的分配器传递到 S1 的构造函数中(更一般地说,S1 中会有多种不同的类型,它们都将使用在构造函数)。但是,我收到下面的编译错误,表明分配器应该是认可构造的。有人可以帮助解释为什么会这样吗?是否发生了一些转换导致需要分配器的认构造版本?

/usr/include/c++/10/scoped_allocator: In instantiation of ‘std::scoped_allocator_adaptor<_Outeralloc,_InnerAllocs>::scoped_allocator_adaptor() [with _Outeralloc = custom::MyAlloc<S1>; _InnerAllocs = {}]’:
/usr/include/c++/10/bits/stl_vector.h:626:35:   required from here
/usr/include/c++/10/scoped_allocator:304:60: error: no matching function for call to ‘custom::MyAlloc<S1>::MyAlloc()’
  304 |       scoped_allocator_adaptor() : _Outeralloc(),_M_inner() { }
      |                                                            ^
d2.cc:17:9: note: candidate: ‘template<class U> custom::MyAlloc<T>::MyAlloc(const custom::MyAlloc<U>&) [with U = U; T = S1]’
   17 |         MyAlloc(const MyAlloc<U> & other) noexcept : _scope(other._scope)  {}
      |         ^~~~~~~
d2.cc:17:9: note:   template argument deduction/substitution Failed:
In file included from d2.cc:4:
/usr/include/c++/10/scoped_allocator:304:60: note:   candidate expects 1 argument,0 provided
  304 |       scoped_allocator_adaptor() : _Outeralloc(),_M_inner() { }
      |                                                            ^
d2.cc:13:9: note: candidate: ‘custom::MyAlloc<T>::MyAlloc(const string&) [with T = S1; std::string = std::__cxx11::basic_string<char>]’
   13 |         MyAlloc(const std::string &scope) noexcept : _scope(scope)  {}
      |         ^~~~~~~
d2.cc:13:9: note:   candidate expects 1 argument,0 provided
d2.cc:10:12: note: candidate: ‘custom::MyAlloc<S1>::MyAlloc(const custom::MyAlloc<S1>&)’
   10 |     struct MyAlloc
      |            ^~~~~~~
d2.cc:10:12: note:   candidate expects 1 argument,0 provided
d2.cc:10:12: note: candidate: ‘custom::MyAlloc<S1>::MyAlloc(custom::MyAlloc<S1>&&)’
d2.cc:10:12: note:   candidate expects 1 argument,0 provided

编译错误

TestNG

解决方法

这一行:custom::vector<S1> cv{sc}; 是问题所在。

因为您使用了方括号,所以它试图调用 vector 的初始化列表构造函数,该构造函数具有一个可选参数,它是一个分配器 - 它默认构造。

查看the list on cppreference中的最后两个构造函数

如果您将该行更改为 custom::vector<S1> cv(sc);,则编译时不会出错。