4

我知道,如果没有 R 值引用, C++ 中的完美转发是不可能的。

但是,我想知道:还有什么需要它们的吗?


例如,这个页面指出了这个例子,其中 R 值引用显然是必要的:

  X foo();
  X x;
  // perhaps use x in various ways
  x = foo();

上面的最后一行:

  • 销毁持有的资源x
  • 从临时返回的资源中克隆资源foo
  • 破坏临时对象,从而释放其资源。

但是,在我看来,如果swap实施得当,一个简单的更改就可以解决问题:

X foo();
X x;
// perhaps use x in various ways
{
    X y = foo();
    swap(x, y);
}

所以在我看来,这种优化不需要r 值引用。(那是对的吗?)

那么,有哪些问题是r 值引用无法解决的(完美转发除外,我已经知道了)?

4

1 回答 1

12

那么,有哪些问题是 r 值引用无法解决的(完美转发除外,我已经知道了)?

Yes. In order for the swap trick to work (or at least, work optimally), the class must be designed to be in an empty state when constructed. Imagine a vector implementation that always reserved a few elements, rather than starting off totally empty. Swapping from such a default-constructed vector with an already existing vector would mean doing an extra allocation (in the default constructor of this vector implementation).

With an actual move, the default-constructed object can have allocated data, but the moved-from object can be left in an unallocated state.

Also, consider this code:

std::unique_ptr<T> make_unique(...) {return std::unique_ptr<T>(new T(...));}

std::unique_ptr<T> unique = make_unique();

This is not possible without language-level move semantics. Why? Because of the second statement. By the standard, this is copy initialization. That, as the name suggests, requires the type to be copyable. And the whole point of unique_ptr is that it is, well, unique. IE: not copyable.

If move semantics didn't exist, you couldn't return it. Oh yes, you can talk about copy elision and such, but remember: elision is an optimization. A conforming compiler must still detect that the copy constructor exists and is callable; the compiler simply has the option to not call it.

So no, you can't just emulate move semantics with swap. And quite frankly, even if you could, why would you ever want to?

You have to write swap implementations yourself. So if you've got a class with 6 members, your swap function has to swap each member in turn. Recursively through all base classes and such too.

C++11 (though not VC10 or VC2012) allows the compiler to write the move constructors for you.

Yes, there are circumstances where you can get away without it. But they look incredibly hacky, are hard to see why you're doing things that way, and most important of all, make things difficult for both the reader and the writer.

When people want to do something a lot for performance sake that makes their code tedious to read, difficult to write, and error-prone to maintain (add another member to the class without adding it to the swap function, for example), then you're looking at something that probably should become part of the language. Especially when it's something that the compiler can handle quite easily.

于 2012-06-23T07:27:46.520 回答