c++ - C++ 标准是否对 vector 赋值函数或构造函数有明确的要求?

标签 c++ g++ clang

在可能有歧义的地方,我指的是 C++14 标准。

使用 https://en.cppreference.com/w/cpp/container/vector作为引用,对模板参数的要求T对于一个 vector 来说是相对稀疏的

The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type is a complete type and meets the requirements of Erasable, but many member functions impose stricter requirements.

事实上,许多页面(例如 insert 的页面)都非常明确地说明了对 T 的要求。 .遗憾的是,构造函数或赋值函数并非如此。这是网站遗漏还是标准遗漏?

动机
这个问题的动机有点复杂。我有一个类Node表示树中的一个节点。每个节点都有一个父节点(由 Node* 表示)和一个子节点列表(由 std::vector<Node, MyAllocator> 表示)。最后一点很有趣。为了确保Node s 继续指向正确的 parent 我实现了一个自定义分配器,它使用指向正确 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 决定以不同方式解释的标准中的歧义,还是其中一个真正的错误?

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

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

最佳答案

您的代码似乎符合 C++17 标准。最强烈的要求来自 std::vector 的复制构造函数:

children(other.children, alloc_t(this))

标准说 ( Table 65 ) 这需要 Node成为Cpp17CopyInsertablestd::vector<Node, PreloadAllocator<Node, Node*>> :

T is Cpp17CopyInsertable into X means that, in addition to T being Cpp17MoveInsertable into X, the following expression is well-formed:

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

and its evaluation causes the following postcondition to hold: The value of v is unchanged and is equivalent to *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;
    }
}

因为你似乎有一个已经正确的封装,这比自定义分配器更有意义(对我来说)。

关于c++ - C++ 标准是否对 vector 赋值函数或构造函数有明确的要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54331715/

相关文章:

c++ - g++ : Compilation failed to deduce reference array in case of temporary object

c++ - std::array 中的编译时间范围检查

C++ std::cout 和字符串打印顺序错误

c++ - 模板替换和 SFINAE 中的私有(private)成员访问

c++ - LLVM-如何通过函数的真实/原始名称获取函数

c++ - 如何将 t[i][j] 转换为指针样式引用

c++ - 在运行时创建具有唯一函数指针的函数

c++ - 未定义对我的类(class)的引用? C++ 初学者

c++ - libtorrent-rasterbar7 : g++ linker unable to find libtorrent/session. hpp

c++ - 在 C++11 中将指针转换为多维 C 样式数组