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

标签 c++ c++11 class-members

在 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/

相关文章:

c++ - 使用迭代器从 C++ 中的 vector 末尾删除元素

c++ - 如何使用win32编写socket通信程序

c++ - 如何获取标准列表中的第二个元素

c++ - 不同类型的初始化是其他类型的导数,还是完全分开的?

c++ - MFC 按钮单击响应转义键

c++ - 模板参数的编译时间比较

c++ - arm-linux-gnueabihf-g++ 是否具有可靠的 C++0x 支持

java - 使用接口(interface)在2个java类之间进行通信

Python - 如果在类中使用了未声明的变量,则强制出错

c++ - 如何在没有 Boost 的情况下将 C++ 成员函数作为线程执行?