Pizer’s Weblog

programming, DSP, math

Posts Tagged ‘references

C++0x: Do people understand rvalue references?

with 8 comments

[last update: 2009-05-27]

Occasionally I happen to see a piece of C++ code from an eager author that tries to utilize rvalue references but doesn’t understand them and gets it wrong. I remember that I had trouble fully grasping the rvalue reference concept. But now, it seems like that was way in the past. I can hardly remember why it was so difficult to understand rvalue references.

It may have something to do with the sources people use to learn about this feature. For example I wouldn’t consider the C++0x wikipedia article to be a good introduction for rvalue references. It seems too short for that. But this wikipedia article is a nice overview of what kind of features can be expected.

Let me just mention the real sources worth reading:

  • N1377: Move Proposal (2002)
  • N1385: Perfect Forwarding Problem (2002)
  • N2027: A Brief Introduction to Rvalue References (2006)
  • N2812: A Safety Problem with Rvalue References (2008)
  • N2844: Fixing a Safety Problem with Rvalue References (Revision 1, 2009)
  • Rvalue References 101by Dave Abrahams

I would recommend N2027 as an introduction and Dave Abraham’s article for more practical details including exception safety and return value optimizations.

Read the rest of this entry »

Written by pizer

April 13, 2009 at 12:50 pm

Surprizing C++ reference-binding rules

with one comment

Isn’t it amazing? You see a very simple piece of code that looks perfectly fine and wonder why it is supposed to be ill-formed:

  struct foo {
    foo();
  private:
    foo(const foo& rhs);
  };

  void func1(const foo&);

  void func2() {
    foo o;
    func1( o ); // ok
    func1( foo() );  // ill-formed, foo's copy-ctor is private
  }

Although an rvalue is allowed to bind to a reference-to-const, the C++ standard allows a compiler to copy an rvalue to another temporary rvalue before binding it to a reference-to-const. Obviously, you need to have a public copy constructor for that.

I really fail to see the merit in this rule. It seems that every available C++ compiler does not create an extra temporary object here and some of these compilers don’t even bother to report an error in this situation (g++ version 3.4.5 accepts the above code).

Fortunately, the upcoming version of the C++ standard removes the CopyConstructible requirement for reference binding. It makes the code above well-formed.

Source: this usenet thread

- P

Written by pizer

March 25, 2009 at 1:56 pm

Follow

Get every new post delivered to your Inbox.