zoukankan      html  css  js  c++  java
  • 智能指针和前置声明之间的小问题

    对比Go等其他语言的工程,C++工程让人痛苦的一件事情就是当工程稍微庞大一点,编译时间就蹭蹭蹭往上爬。一般来说看过Effective C++这本书或者其他类似书籍的人都知道要解决编译时长的问题,就要解决好和头文件之间的依赖关系。所以在任何必要的时候要首先考虑使用前置声明而不是之间include头文件。也就是说,在定义类的时候成员变量如果是自定义类型,可以考虑将其声明为指针类型或者是配合智能指针。函数传参时也是一样,使用指针或者引用。

    对于一个C工程来说,因为没有智能指针和引用的概念,所以都是直接使用指针配合前置声明。用起来得心应手。

    但是C++工程里,有时候为了方便和省心,更多时候指针类型的成员变量会使用智能指针包一下。这个时候有可能会出现编译通不过的情况:

    MSVC:

    error C2338: can't delete an incomplete type
    warning C4150: deletion of pointer to incomplete type 'base';

    Clang:

    error : invalid application of 'sizeof' to an incomplete type 'base'
                        static_assert(0 < sizeof (_Ty),
                                          ^~~~~~~~~~~~
    note: in instantiation of member function 'std::default_delete<base>::operator()' requested here
                                this->get_deleter()(get());
                                ^
        ./main.h(6,8) :  note: in instantiation of member function 'std::unique_ptr<base, std::default_delete<base> >::~unique_ptr' requested here
        struct test
               ^
    ./main.h(5,8) :  note: forward declaration of 'base'
        struct base;

    看到这里,还是要感谢下clang的输出,比较清楚地把问题的本质原因找出来了。但是等等,我哪里调用了智能指针的析构函数?

    稍微有点警觉的情况下,你应该反应过来是默认的析构函数在做析构智能指针这事情。

    我们先来做一个尝试,把默认的析构函数显示写出来,然后按习惯把析构函数的定义放到cpp文件里。这时你会发现,编译通过并且能正常运行。

    问题来了,为什么显示声明析构函数并将其定义挪到cpp里,这个问题就解决了呢?

    还是来一段标准里的话吧:

    12.4/4
    If a class has no user-declared destructor, a destructor is implicitly declared as defaulted(8.4). An implicitly declared destructor is an inline public member of its class.

    所以这个隐式的inline析构函数在调用智能指针的析构函数析构管理的指针对象时,需要知道该对象的大小。而此时只能看到前置声明而无法看到定义也就无从知道大小,只能GG了。

    1 #pragma once
    2 
    3 struct base
    4 {
    5   int x;
    6 };
    base.h
     1 #pragma once
     2 
     3 #include <memory>
     4 
     5 struct base;
     6 struct test
     7 {
     8   std::unique_ptr<base> base_;
     9 
    10   void print_base() const;
    11 };
    test.h
     1 #include "main.h"
     2 #include "base.h"
     3 
     4 #include <cstdio>
     5 
     6 void
     7 test::print_base() const
     8 {
     9   std::printf("%d
    ", base_->x);
    10 }
    test.cpp
    1 #include "test.h"
    2 
    3 int main()
    4 {
    5   test t;
    6   t.print_base();
    7 
    8   return 0;
    9 }
    main.cpp
  • 相关阅读:
    AcWing 3772. 更新线路(BFS)
    AcWing 3760. 最大剩余油量(树的最长路径)
    AcWing 3771. 选取石子
    洛谷P2014—选课(树形DP)
    吴恩达机器学习ex1
    洛谷P1122—最大子树和(树形DP)
    论文中关于要使用600线的python代码
    mysql 笛卡尔积
    mysql 外键
    写参考文献有感
  • 原文地址:https://www.cnblogs.com/wpcockroach/p/7284263.html
Copyright © 2011-2022 走看看