C ++标准是否对向量分配函数或构造函数提出了明确要求?

时间:2019-01-23 16:31:36

标签: c++ g++ clang

在可能模棱两可的地方,我指的是C ++ 14标准。

使用https://en.cppreference.com/w/cpp/container/vector作为参考,向量对模板参数T的要求相对稀疏

  

对元素施加的要求取决于对容器执行的实际操作。通常,要求元素类型是完整类型并满足Erasable的要求,但是许多成员函数提出了更严格的要求。

实际上,许多页面(例如insert的页面)对于T的要求都非常明确。遗憾的是,对于构造函数或assign函数而言,情况并非如此。是网站还是标准遗漏了?

动机
这个问题的动机有点复杂。我有一个类Node代表树中的节点。每个节点都有一个父级(由Node*表示)和一个子级列表(由std::vector<Node, MyAllocator>表示)。最后一点很有趣。为了确保Node继续指向正确的父级,我实现了一个自定义分配器,该分配器用指向正确的Node的指针“预加载”每个构造函数调用。的代码如下

#ifndef PRElOAD_ALLOCATOR_H
#define PRElOAD_ALLOCATOR_H

#include <tuple>
#include <utility>
#include <memory>
#include <vector>

/**
 * @class PreloadAllocator
 * Provides a generic allocator that is able to 'preload' some arguments for the
 * construct function. Note that these arguments are *always* loaded at the
 * front of any constructor call so modified move, copy constructors need to
 * created to match.
 * This allocator will only work with simple containers like vector that do not
 * modify the type of the allocator being used. *It will not work* with types
 * like list and map that internally represent the data in a different format.
 * This is because the constructors for these objects behave differently and it
 * is not simple to know how to insert the extra arguments into such a call.
 */
template <typename T, typename... Args>
class PreloadAllocator {
  public:

    // Standard allocator typedefs
    using value_type      = T;
    using pointer         = T*;
    using const_pointer   = const T*;
    using reference       = T&;
    using const_reference = const T&;
    using size_type       = std::size_t;
    using difference_type = std::ptrdiff_t;

    PreloadAllocator(Args&&... args)
      : tup(std::forward_as_tuple(args...) ) {}

    template <typename U>
      PreloadAllocator(const PreloadAllocator<U, Args...>& other)
      : tup(other.tup) {}

    pointer allocate(size_type count, const_pointer hint = 0) {
      return m_defaultAlloc.allocate(count, hint);
    }

    void deallocate(pointer ptr, size_type count) {
      return m_defaultAlloc.deallocate(ptr, count);
    }

    template <typename... Ts>
      void construct(T* ptr, Ts&&... ts) {
        // First preload the constructor arguments with the allocator's
        // versions, then add on the rest, and let the default allocator do the
        // rest.
        return construct_impl<Ts...>(
            ptr, std::forward<Ts>(ts)..., std::index_sequence_for<Args...>{});
      }

    // Hold the arguments that we will preload into every constructor call
    const std::tuple<Args...> tup;
  private:
    // Compose the default STL allocator to use its version of allocate and
    // deallocate.
    std::allocator<T> m_defaultAlloc;
    // Actual function that does the constructing
    template <typename... Ts, std::size_t... Is>
      void construct_impl(T* ptr, Ts&&... ts, std::index_sequence<Is...>) {
        return m_defaultAlloc.construct(
          ptr, std::get<Is>(tup)..., std::forward<Ts>(ts)...);
      }
};

template <typename T, typename... Args>
bool operator==(
    const PreloadAllocator<T, Args...>& lhs,
    const PreloadAllocator<T, Args...>& rhs)
{
  return lhs.tup == rhs.tup;
}

template <typename T, typename... Args>
bool operator!=(
    const PreloadAllocator<T, Args...>& lhs,
    const PreloadAllocator<T, Args...>& rhs)
{
  return !(lhs==rhs);
}

#endif //> !PRElOAD_ALLOCATOR_H

class Node {
  public:
    using alloc_t = PreloadAllocator<Node, Node*>;
    using vec_t = std::vector<Node, alloc_t>;

    Node(Node* parent, int data)
      : parent(parent), data(data), children(alloc_t(this) ) {}
    Node(Node* parent, const Node& other)
      : parent(parent), data(other.data), children(other.children, alloc_t(this) ) {}
    Node(Node* parent, Node&& other)
      : parent(parent), data(std::move(other.data) ), children(std::move(other.children), alloc_t(this) ) {}

    // Copy/Move constructing is not going to give us the correct parent!
    Node(const Node&) = delete;
    Node(Node&&) = delete;

    Node* parent;
    int data;
    vec_t children;
};

int main() {
  Node root(nullptr, 0);
}

在g ++中编译此代码时,它将编译并运行良好。但是,当我用clang编译时,出现以下错误

In file included from alloc_test.cxx:3:
/Library/Developer/CommandLineTools/usr/include/c++/v1/vector:1275:9: error: no matching member function for call to 'assign'
        assign(_Ip(__x.begin()), _Ip(__x.end()));
        ^~~~~~
alloc_test.cxx:15:55: note: in instantiation of member function 'std::__1::vector<Node, PreloadAllocator<Node, Node *> >::vector' requested here
      : parent(parent), data(std::move(other.data) ), children(std::move(other.children), alloc_t(this) ) {}
                                                      ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/vector:588:10: note: candidate function not viable: no known conversion from '_Ip' (aka 'move_iterator<__wrap_iter<Node *> >') to
      'std::__1::vector<Node, PreloadAllocator<Node, Node *> >::size_type' (aka 'unsigned long') for 1st argument
    void assign(size_type __n, const_reference __u);
         ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/vector:576:9: note: candidate template ignored: requirement '!__is_forward_iterator<move_iterator<__wrap_iter<Node *> > >::value' was not satisfied
      [with _InputIterator = std::__1::move_iterator<std::__1::__wrap_iter<Node *> >]
        assign(_InputIterator __first, _InputIterator __last);
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/vector:586:9: note: candidate template ignored: requirement 'is_constructible<value_type, typename iterator_traits<move_iterator<__wrap_iter<Node *>
      > >::reference>::value' was not satisfied [with _ForwardIterator = std::__1::move_iterator<std::__1::__wrap_iter<Node *> >]
        assign(_ForwardIterator __first, _ForwardIterator __last);
        ^
/Library/Developer/CommandLineTools/usr/include/c++/v1/vector:592:10: note: candidate function not viable: requires single argument '__il', but 2 arguments were provided
    void assign(initializer_list<value_type> __il)
         ^
1 error generated.

那么,这是g ++和clang决定以不同的方式解释的标准中的模棱两可吗,还是对其中一个是真正的错误?

是否正在尝试编写这种预加载分配器,这是对标准的不可原谅的滥用?

*编辑:*修复了代码片段中缺少的数据成员。

1 个答案:

答案 0 :(得分:1)

您的代码似乎对C ++ 17标准有效。最强烈的要求来自std::vector的副本构造函数:

children(other.children, alloc_t(this))

标准说(Table 65)要求Node成为{em> Cpp17CopyInsertable 到std::vector<Node, PreloadAllocator<Node, Node*>>中:

  

TCpp17CopyInsertableX的意思是,除了T Cpp17MoveInsertable 插入X之外,以下表达式格式正确:

allocator_traits<A>::construct(m, p, v)
     

及其评估会导致以下后继条件成立:v的值不变,并且等效于*p

Cpp17MoveInsertable的要求与之相似,不同之处在于v是一个右值,并且发布条件不同。

查看clang的错误时,似乎编译器正在检查MoveConstructible的要求:

is_constructible<
    value_type, 
    typename iterator_traits<move_iterator<__wrap_iter<Node *> >::reference>::value

...与Cpp17MoveInsertable的...不同。


从设计的角度来看,我会亲自删除该自定义分配器,而是在需要时手动更新parent成员,例如:

Node(Node* parent, const Node& other) 
    : parent(parent), data(other.data), children(other.children) {
    fix_parent_in_childrens();
}

void fix_parent_in_childrens() {
    for (Node &node: children) {
        node.parent = this;
    }
}

由于您似乎已经拥有正确的封装,对我来说,这比自定义分配器更有意义。