Search code examples
c++unique-ptrincomplete-type

unique_ptr with forward declared incomplete type won't compile


I am trying to follow the PIMPL idiom for C++. I have thus created a class AgeDetect which will be my user facing interface, and AgeDetectImpl which contains all the implementation. I am forward declaring AgeDetectImpl and using an std::unique_ptr to store it as a private member of AgeDetect. I followed the instructions from this question and have implemented a destructor so I am not sure what the issue is.

AgeDetect.h

#ifndef AGE_DETECT_H
#define AGE_DETECT_H

#include <memory>
#include <opencv2/opencv.hpp>

class AgeDetect {
    class AgeDetectImpl;
    std::unique_ptr<AgeDetectImpl> m_ageDetectImplPtr = nullptr;
public:
    AgeDetect(std::string token);
    ~AgeDetect();

    std::string getAge(std::string imagepath);
    std::string getAge(uint8_t* buffer, size_t rows, size_t cols);
    std::string getAge(const cv::Mat& image);
};


#endif

AgeDetect.cpp

#include "ageDetect.h"
#include "ageDetectImpl.h"

AgeDetect::~AgeDetect() = default;

AgeDetect::AgeDetect(std::string token) {
    //m_ageDetectImplPtr = std::make_unique<AgeDetectImpl>(token);
    }

Error Message

 error: invalid application of ‘sizeof’ to incomplete type ‘AgeDetect::AgeDetectImpl’
  static_assert(sizeof(_Tp)>0,

Edit Fixed header guards


Solution

  • As mentioned by CuriouslyRecurringThoughts and Jarod42, the issue was due to the assignment of nullptr to m_ageDetectImplPtr

    The following code works

        class AgeDetectImpl;
        class AgeDetect {
        public:
            AgeDetect(std::string token);
            ~AgeDetect();
    
            std::string getAge(std::string imagepath);
            std::string getAge(uint8_t* buffer, size_t rows, size_t cols);
            std::string getAge(const cv::Mat& image);
    
        private:
            std::unique_ptr<AgeDetectImpl> m_ageDetectImplPtr;
        };