为了防止复制一个类,你可以很容易地声明一个私有(private)的复制构造函数/赋值操作符。但是你也可以继承boost::noncopyable
。
在这种情况下使用 boost 有什么优点/缺点?
最佳答案
我没有看到任何文档优势:
#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
派生以及这是否会花费我要容易得多。特别是如果我不是完整继承层次结构的作者。
关于c++ - boost::noncopyable 的优点是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7823990/