复制构造函数没有调用,但编译器抱怨没有 [英] Copy constructor not called, but compiler complains that there's no

查看:111
本文介绍了复制构造函数没有调用,但编译器抱怨没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码:

#include <boost/noncopyable.hpp>

enum Error { ERR_OK=0 };

struct Filter : private boost::noncopyable
{
  Filter() {}
  virtual ~Filter() {}

  virtual int filter(int* data) const = 0;

};

struct  SpecialFilter : public Filter, private boost::noncopyable
{
  inline SpecialFilter(unsigned int min, unsigned int max) : min(min), max(max) {}
  virtual ~SpecialFilter() {}

  virtual int filter(int* data) const
  {
    // ...
    return ERR_OK;
  }

  unsigned int min;
  unsigned int max;
};

struct AClass
{
  AClass() {}
  AClass(const AClass& other) {}
  ~AClass() {}

  int specialFilter(int channel, int minThreshold, int maxThreshold)
  {
    // ...
    return filter(channel, SpecialFilter(123, 321));
  }

  int filter(int channel, const Filter& filter)
  {
    // ...
    return ERR_OK;
  }

};



我的编译器(GCC 4.2)抱怨:

My compiler (GCC 4.2) complains:

- warning: direct base ‘boost::noncopyable_::noncopyable’ inaccessible in ‘SpecialFilter’ due to ambiguity
- noncopyable.hpp: In copy constructor ‘Filter::Filter(const Filter&)’:
- noncopyable.hpp:27: error: ‘boost::noncopyable_::noncopyable::noncopyable(const boost::noncopyable_::noncopyable&)’ is private
- synthezised method first required here: [return filter(channel, SpecialFilter(123, 321));]

但是我不调用复制构造函数!

But I don't call the copy constructor!

推荐答案

复制构造函数总是由编译器隐式调用。

You never call copy constructor. The copy constructor is always called for you implicitly by the compiler. So you need to learn to recognize situations when it might be called.

当您将一个const引用附加到临时对象时

When you attach a const reference to a temporary object

...
return filter(channel, SpecialFilter(123, 321));
...

编译器有权执行临时对象的副本,需要一个可访问的复制构造函数(即使它不会被实际调用)。这是导致你的情况下的问题。

the compiler has the right to perform a copy of the temporary object and require an accessible copy constructor (even if it won't be actually called). This is what is causing the problem in your case.

换句话说,当你使一些类型不可复制时,你也放弃了附加const引用的可能性该类型的临时对象。

In other words, when you make some type non-copyable, you also give up the possibility to attach const references to temporary objects of that type.

这篇关于复制构造函数没有调用,但编译器抱怨没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆