gpt4 book ai didi

c++11 - 默认的析构函数 C++11 样式应该放在哪里,头文件还是 cpp?

转载 作者:行者123 更新时间:2023-12-04 16:27:01 29 4
gpt4 key购买 nike

在 C++11 中,可以使用“= default”指定构造函数、析构函数和复制/移动运算符的默认实现。将“= default”放在哪里,在头文件中,类定义在哪里,或者在源文件(cpp)中?

在头文件 Test.h 中:

class Test
{
public:
~Test() = default;
};

在源文件 Test.cpp 中:
class Test
{
public:
~Test();
};

#include "Test.h"
Test::~Test() = default;

最佳答案

我不得不不同意rubenvb。您不必将显式默认析构函数放在头文件中。
事实上,在一个用例中,将显式默认析构函数放在 .cpp 文件中是完全有效的(并且是必要的)。

考虑在头文件中转发声明一个类并将其与智能指针模板之一一起使用的情况。由于隐式析构函数没有前向声明类的完整声明,它不能正确地进行删除。因此,您需要将析构函数定义移动到 C++ 文件中,您应该可以在其中访问完整的声明。

在 A.hpp 中:

#pragma once
#include <memory>
class B;

class A
{
private:
std::unique_ptr<B> my_b;
public:
// ~A() = default;
// defining the default destructor would fail as
// class B is still a partial class here
~A();
};

在 A.cpp 中:
#include "A.hpp"

// the previously forward declared class B is now included here
#include "B.hpp"

// we can use the default destructor here as B is
// no longer a partial class
A::~A() = default;

关于c++11 - 默认的析构函数 C++11 样式应该放在哪里,头文件还是 cpp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38242200/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com