c++ - boost::noncopyable 的优点是什么

标签 c++ boost noncopyable

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

相关文章:

c++ - 强制一个特定的构造函数只在某些代码中使用,别处

c++ - 防止在 C++ 中调用基本赋值运算符

c++ - 为什么不能使用显式模板参数调用模板 friend 功能?

c++ - boost 链接失败

c++ - 在 C++ 中创建不可复制但可移动的对象

c++ - 在 C++11 中显式删除了成员函数,从不可复制的基类继承是否仍然值得?

c++ - 在 QObject 派生类中重复 Q_DISABLE_COPY

c++ - 使用嵌套的 for 循环进行向上和向下计数

c++11 中 boost::filesystem::copy_file() 缺少符号

c++ - Code::Blocks 和 boost 1.55:存在动态库时不使用静态库