Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference or pointer to std::vector of incomplete type

As answered here: How can an incomplete type be used as a template parameter to vector here? usage of incomplete type as template argument when instantiating a template component can result in undefined behaviour. But does that rule hold true when we have only pointer/reference to template component with incomplete type as argument? Does the instatiation happen in this case too?

For example:

// SomeAlgoInterface.hpp

#include <vector> 

struct Result; // forward declaration

class SomeAlgoInterface
{
  public:

   virtual ~SomeAlgoInterface() = default; 

  public:

    // the following line is definitely OK, ...
    virtual void f1(const Result & result) = 0; 

    // ... but I'm not quite sure about the following one
    virtual void f2(const std::vector<Result> & results) = 0; 
};

In other words, is the code above valid or not?

like image 268
ykim Avatar asked Dec 09 '15 21:12

ykim


1 Answers

The declaration is correct, so long as you don't call f2.

The compiler doesn't need to know the internal of Result class if you don't call f2. There's no storage allocation in the declaration.

If some compilation unit call f2, you need to supply the complete type for Result class, or you need another reference parameter to call f2:

void another_f(SomeAlgoInterface& i, std::vector<Result>& results)
{
    i.f2(results);  
}
like image 64
alangab Avatar answered Nov 02 '22 22:11

alangab