要防止复制一个类,您可以很容易地声明一个私有(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/37057849/