What's the most reliable way to prohibit a copy constructor in C++?

前端 未结 6 2073
情话喂你
情话喂你 2020-11-28 10:43

Sometimes it\'s necessary to prohibit a copy constructor in a C++ class so that class becomes \"non-copyable\". Of course, operator= should be prohibited at the

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 11:21

    As other answers suggest something else, and doesn't really attempt to answer the question, so here is my attempt:

    So which approach is better? It depends on how you define prohibit copy?

    If you want to prevent others (only non-friend classes and functions) from copying while allowing friends and member-functions to copy, then second approach is the way to go.

    If you want to prevent everyone (friends, non-friends, member-functions) from copying, then first approach is the only correct solution.

    Note that the second approach does not prevent friends and member-functions from copying (that is, from calling the copy-functions). 1

    1. If you don't properly define them in the second case, then copy wouldn't work, as expected, but that is a different thing altogether. But the point is that second case doesn't prevent from calling the copy-functions. The compiler wouldn't generate any error message.

提交回复
热议问题