mardi 5 janvier 2016

C++11 container of unique_ptr of forward declared class

g++ -std=c++11 does not compile a class that contains a container that contains unique pointers that point to a forward declared class. Questions:

  • Why?
  • Is there a reasonable workaround?

Code example:

#include <vector>
#include <memory>

// variant 1: compiles
class Bar {};
using BarPtr = std::unique_ptr<Bar>;

// variant 2: compiles
using BarPtr = std::shared_ptr<class Bar>;

// variant 3: compilation fails below
using BarPtr = std::unique_ptr<class Bar>;

// end of variants

class Foo {
    std::vector<BarPtr> vec;
 public:
    Foo() {} // compilation of variant 3 fails here:
             // invalid application of ‘sizeof’ to incomplete type ‘Bar’
};

I have seen How to forward declare a class to be used in a standard container of unique_ptr and Is std::unique_ptr<T> required to know the full definition of T?, but do not find convincing answers to my above questions.

Aucun commentaire:

Enregistrer un commentaire