C++ 在C+中使用继承防止类的复制/移动/实例化+;17
除了显式删除构造函数和赋值运算符以禁止复制/移动/实例化类之外,另一种方法是引入空的“标记”基类并继承它们以获得相同的结果。以下是我对此类解决方案的实施:C++ 在C+中使用继承防止类的复制/移动/实例化+;17,c++,inheritance,optimization,c++17,C++,Inheritance,Optimization,C++17,除了显式删除构造函数和赋值运算符以禁止复制/移动/实例化类之外,另一种方法是引入空的“标记”基类并继承它们以获得相同的结果。以下是我对此类解决方案的实施: class Non_copyable { protected: Non_copyable() = default; ~Non_copyable() = default; Non_copyable(const Non_copyable&) = delete;
class Non_copyable {
protected:
Non_copyable() = default;
~Non_copyable() = default;
Non_copyable(const Non_copyable&) = delete;
Non_copyable& operator=(const Non_copyable&) = delete;
Non_copyable(Non_copyable&&) = default;
Non_copyable& operator=(Non_copyable&&) = default;
};
//Non_moveable is meant to be used together with Non_copyable to disallow both copying and moving
class Non_moveable {
protected:
Non_moveable() = default;
~Non_moveable() = default;
Non_moveable(const Non_moveable&) = default;
Non_moveable& operator=(const Non_moveable&) = default;
Non_moveable(Non_moveable&&) = delete;
Non_moveable& operator=(Non_moveable&&) = delete;
};
class Abstract {
protected:
Abstract() = delete;
~Abstract() = delete;
};
我的问题如下:
protected
,以防止访问派生类之外的成员函数(它们必须在派生类中可访问)private
、protected
和public
都是一样的,但也许我在这里遗漏了一些东西- 我知道空基优化,但是,cppreference提到了一个例外:
“如果其中一个空基类也是第一个非静态数据成员[…]的类型或基,则禁止空基优化。”
这是否意味着在这种情况下:
Y
如果我遗漏了任何其他方面,例如我的解决方案无法按预期工作的某些场景或一些隐藏的性能损失,请提及它们。只需删除构造函数;这是常见的习惯用法,因此其他程序员也会理解。
struct X: Non_copyable {};
struct Y: Non_copyable {
X x;
};