我没有看到任何文档优势:
#include <boost/noncopyable.hpp>
struct A
: private boost::noncopyable
{
};
对比:
struct A
{
A(const A&) = delete;
A& operator=(const A&) = delete;
};
当您添加仅移动类型时,我什至认为文档具有误导性。以下两个示例不可复制,但可以移动:
#include <boost/noncopyable.hpp>
struct A
: private boost::noncopyable
{
A(A&&) = default;
A& operator=(A&&) = default;
};
对比:
struct A
{
A(A&&) = default;
A& operator=(A&&) = default;
};
在多重继承下,甚至会出现空间惩罚:
#include <boost/noncopyable.hpp>
struct A
: private boost::noncopyable
{
};
struct B
: public A
{
B();
B(const B&);
B& operator=(const B&);
};
struct C
: public A
{
};
struct D
: public B,
public C,
private boost::noncopyable
{
};
#include <iostream>
int main()
{
std::cout << sizeof(D) << '\n';
}
对我来说这是打印出来的:
3
但是这个,我认为有更好的文档:
struct A
{
A(const A&) = delete;
A& operator=(const A&) = delete;
};
struct B
: public A
{
B();
B(const B&);
B& operator=(const B&);
};
struct C
: public A
{
C(const C&) = delete;
C& operator=(const C&) = delete;
};
struct D
: public B,
public C
{
D(const D&) = delete;
D& operator=(const D&) = delete;
};
#include <iostream>
int main()
{
std::cout << sizeof(D) << '\n';
}
输出:
2
我发现声明我的复制操作比推理我是否多次从boost::non_copyable 派生以及这是否会让我付出代价要容易得多。特别是如果我不是完整继承层次结构的作者。