Must a deleted constructor be private?

别等时光非礼了梦想. 提交于 2019-11-27 15:51:27

问题


class A
{
public:
    A() = default;
    A(const A&) = delete;
};

class A
{
public:
    A() = default;

private:
    A(const A&) = delete;
};

Are these two definitions always identical to each other in any cases?


回答1:


They are different only wrt the produced diagnostics. If you make it private, an additional and superfluous access violation is reported:

class A
{
public:
    A() = default;
private:
    A(const A&) = delete;
};

int main()
{
    A a;
    A a2=a;
}

results in the following additional output from GCC 4.8:

main.cpp: In function 'int main()':
main.cpp:6:5: error: 'A::A(const A&)' is private
     A(const A&) = delete;
     ^
main.cpp:12:10: error: within this context
     A a2=a;
          ^

hence my recommendation to always make deleted methods public.




回答2:


I want to extend Daniel Frey's answer. Instead of making deleted methods always public, I would rather give these methods the access modifier you would (hypothetically) give these methods if they would not be deleted. (I do not like always in case a programmer has an option. If it would indeed be carved in stone to make deleted methods public, it should be enforced by the language itself.)

Some rules of thumb/guidelines:

  • Copy and move assignment operators will be public in concrete and abstract classes for most cases.
  • Copy and move constructors will be public in concrete classes for most cases.
  • Copy and move constructors will be protected in abstract classes for most cases.
  • Copy and move constructors will be private in concrete final classes that can only be instantiated by friends for most cases.

In all cases, you make an announcement to the appropriate users of a class instead of all users of a class.



来源:https://stackoverflow.com/questions/18931133/must-a-deleted-constructor-be-private

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!