类外的默认构造函数/析构函数? [英] Default constructor/destructor outside the class?
问题描述
根据C ++ 11标准( =默认
在类的定义之外),以下内容是合法的吗?
//在头文件中
class Test
{
public:
Test();
〜Test();
};
//在cpp文件中
Test :: Test()= default;
Test ::〜Test()= default;是的,一个特殊的成员函数可以是默认定义的,它可以是一个特定的成员函数,它可以是一个特定的成员函数。 out-of-line在.cpp文件中。意识到,通过这样做,内联默认函数的一些属性将不适用于您的类。例如,如果你的拷贝构造函数是默认定义的,那么你的类不会被认为是可以复制的(它也不能被识别为POD)。类似地,默认定义的out-of-line析构函数将取消你的类型是不重要的(或POD)。
- 内联复制构造函数和控制它在哪里定义(可能控制生成的模板定义它将需要),但不希望手动定义一个手工成员初始化列表,这将是费力的并可能在维护下过时。
Is the following legal according to the C++11 standard (= default
outside the definition of the class) ?
// In header file
class Test
{
public:
Test();
~Test();
};
// In cpp file
Test::Test() = default;
Test::~Test() = default;
解决方案 Yes, a special member function can be default-defined out-of-line in a .cpp file. Realize that by doing so, some of the properties of an inline-defaulted function will not apply to your class. For example, if your copy constructor is default-defined out-of-line, your class will not be considered trivially copyable (which also disqualifies it from being recognized as a POD). Similarly, a default-defined out-of-line destructor will disqualify your type from being trivial (or POD).
This can be useful if you wish to have a non-inline copy-constructor and control over where it is defined (perhaps to take control over generated template definitions it will require), but don't wish to manually define it yourself with a hand-crafted member-initializer list, which would be laborious and could go stale under maintenance.
这篇关于类外的默认构造函数/析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!