1

Basically this is a question about semantics. I'm using Cereal library for (de)serialization in C++, and found its coding style interesting:

cereal::PortableBinaryInputArchive ar(instream);
int out;
ar(out);
// int is successfully deserialized from input stream here.

The tricky part is that I do not pass in the "out" by reference and ar() can still modify its value. Well in fact, the author just overrides the operator "()". And I found the corresponding lines in the source files.

OutputArchive & operator=( OutputArchive const & ) = delete;

  //! Serializes all passed in data
  /*! This is the primary interface for serializing data with an archive */
  template <class ... Types> inline
  ArchiveType & operator()( Types && ... args )
  {
    self->process( std::forward<Types>( args )... );
    return *self;
  }

I'm quite at a loss, especially the first line ("= delete") and things regarding "std::forward( args )...". I only saw some cases in which macros like va_arg are used and it's the first time that I've encountered something like this. Besides, what does "&&" stand for? Could anyone throw some light upon it?

4

1 回答 1

4

我很茫然,尤其是第一行(“=删除”)

“= delete”有效地确保不能调用operator=(赋值运算符...),并且不会生成默认值(赋值运算符)。将 operator= 设为私有,并且不提供定义是一样的。此运算符也可用于普通函数,在这种情况下,类似地禁止使用它(请参阅 c++ 11 标准,第 8.4.3 节):

struct B
{
  void foo(){}
};

struct D : B
{
  void foo() = delete;
};

int main() {
    D().foo(); //Fails to compile here - deliberate!!!
    return 0;
}

请注意,调用 foo 的类型很重要。它仍然可以在基本类型上调用,就像即使禁止派生赋值仍然可以切片一样(参见下面的示例):

struct B{};

struct D : B
{
  D& operator=(const D&) = delete;    
};

int main() {
    B b;
    D d1, d2;
    b = d1; //Compiles fine - slices
    d1 = d2; //Fails to compile...
    return 0;
}

以及关于“std::forward(args)...”的事情。

std::forward 允许参数的完美转发(即参数类型 wrt 到 r/l 价值和修饰符不会改变(参考)

我只看到一些使用像 va_arg 这样的宏的情况,这是我第一次遇到这样的事情。

template <class ... Types>
void foo( Types&& ...);

... 在这种情况下,称为可变参数模板 (google)。

此外,“&&”代表什么?任何人都可以对此有所了解吗?

&& 代表右值引用或通用引用,具体取决于上下文。在这种情况下,它是一个通用参考(Scott Meyers 在此处有一篇关于通用参考的好文章)。

编辑:通用引用现在被正确地称为转发引用(n4164)

于 2015-06-05T09:23:42.713 回答