gpt4 book ai didi

c++ - 在没有任何构造函数的类的情况下,C++11 中自动生成的类成员函数

转载 作者:太空狗 更新时间:2023-10-29 20:40:10 32 4
gpt4 key购买 nike

在 C++11 中,我定义了一个具有以下一般形式的结构:

struct MyStruct
{
static void myFunc( void );

//constructors
MyStruct( void ) = delete;
};

无法创建类型为 MyStruct 的任何对象,因为默认构造函数已标记为已删除。即使方法 myFunc 也不能创建该类的实例。不过该结构仍然有用,因为 MyStruct::myFuncpublic 并且可以从外部调用。

我现在的问题是:由于不可能创建类型为 MyStruct 的任何对象,编译器是否会为复制构造函数、 地址运算符或 析构函数?

请注意:在我的实际代码中,我确实必须根据静态类成员函数来实现功能,因为我必须使用部分模板类特化来模拟部分模板函数特化。所以我想知道如何让类(class)尽可能精简。

修改:根据@Praetorian的评论和回答,去掉了自动生成地址运算符的备注。

最佳答案

编译器将为您的类隐式声明析构函数和复制构造函数,但由于您无法创建该类的实例,因此您的程序将永远无法使用任何一个析构函数或复制构造函数,因此它们都不会被隐式定义

§12.4 [class.dtor]

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.

5   A destructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used (3.2) to destroy an object of its class type (3.7) or when it is explicitly defaulted after its first declaration.

§12.8 [class.copy]

7   If the class definition does not explicitly declare a copy constructor, one is declared implicitly. If the class definition declares a move constructor or move assignment operator, the implicitly declared copy constructor is defined as deleted; otherwise, it is defined as defaulted (8.4). The latter case is deprecated if the class has a user-declared copy assignment operator or a user-declared destructor.

13   A copy/move constructor that is defaulted and not defined as deleted is implicitly defined if it is odr-used (3.2) or when it is explicitly defaulted after its first declaration.

至于地址运算符 (operator&),编译器永远不会为您隐式生成该运算符重载。运算符的内置地址可以应用于任何左值类型以获取其地址,但这是一种语言功能,与为用户定义的类型重载该运算符无关。

关于c++ - 在没有任何构造函数的类的情况下,C++11 中自动生成的类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25193041/

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