incomplete type for std::unordered_set compiling e

2019-08-10 01:04发布

问题:

Consider the code related to a previous SO question C++ cyclic dependency confusion with adjacency list representation

#include <cstddef>
#include <unordered_set>

class Node;

class Hash {
public:
    std::size_t operator()(const Node &node) const;
};

class Node {
public:
    int data;
    std::unordered_set<Node, Hash> links;
};

inline size_t Hash::operator()(const Node &node) const {
    return node.data;
}

int main()
{

}

This code does not compile when using g++4.9.2 or g++5, however compiles with clang++3.5.

The error spit out by g++ starts with

error: invalid application of 'sizeof' to incomplete type 'Node' : std::aligned_storage<sizeof(_Tp), std::alignment_of<_Tp>::value>

Question: Does Node have to be a complete type when declaring an std::unordered_set? Looks like either g++ or clang++ is wrong in this case.

PS: I know this situation can be avoided by using a std::shared_ptr<Node> instead, however would like to understand the behaviour in the code above.

回答1:

It is undefined behavior to instantiate a standard library container with an incomplete type. [res.on.functions]/1, 2.5:

1 In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C++ standard library depends on components supplied by a C++ program. If these components do not meet their requirements, the Standard places no requirements on the implementation.

2 In particular, the effects are undefined in the following cases:

  • [...]
  • if an incomplete type (3.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.

Both implementations are correct.

There is currently a proposal to add incomplete type support to some containers, but it is limited to vector, list and forward_list.