【问题标题】:unique_ptr with forward declared incomplete type won't compile [duplicate]具有前向声明的不完整类型的 unique_ptr 不会编译 [重复]
【发布时间】:2019-06-26 21:56:07
【问题描述】:

我正在尝试遵循 C++ 的 PIMPL 习语。因此,我创建了一个类AgeDetect,它将是我的面向用户的界面,而AgeDetectImpl 则包含所有实现。我转发声明AgeDetectImpl 并使用std::unique_ptr 将其存储为AgeDetect 的私有成员。我按照this question 中的说明执行了析构函数,所以我不确定问题出在哪里。

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: invalid application of ‘sizeof’ to incomplete type ‘AgeDetect::AgeDetectImpl’
  static_assert(sizeof(_Tp)>0,

编辑 固定头卫

【问题讨论】:

  • 你需要一个 pimpl 删除器:stackoverflow.com/questions/9954518
  • 此外,您的标头保护 __AGE_DETECT_H__ 是一个保留标识符,因为它有两个下划线,还因为它在全局(预处理器)范围内以一个下划线开头。
  • @Eljay 你能详细说明什么是 pimpl 删除器吗?从那个线程,看起来我的包装类需要删除,我的 ~AgeDetect();
  • @Eljay 并感谢您提供有关标头后卫的信息,我已解决此问题
  • 能不能一开始就赋值给nullptr?目前无法轻松访问编译器

标签: c++ unique-ptr incomplete-type


【解决方案1】:

正如 CuriouslyRecurringThoughts 和 Jarod42 所述,问题是由于将 nullptr 分配给 m_ageDetectImplPtr

以下代码有效

    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;
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2016-01-17
    • 2013-11-04
    • 2011-10-22
    相关资源
    最近更新 更多