如何优雅的写C++代码 Obotcha介绍(转载in instantiation of member function requested here异常)

本文探讨了C++中使用智能指针时遇到的编译问题,特别是关于前置声明导致的错误。当智能指针管理的对象类型只有前置声明而未完整定义时,会导致编译失败。通过分析MSVC和Clang的错误信息,指出问题源于隐式默认析构函数尝试销毁未完全定义的对象。解决方法是显式声明析构函数,并将其定义移至cpp文件中。这一做法避免了在头文件中因前置声明引发的编译错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

z智能指针和前置声明之间的小问题 

对比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\n", 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值