Pizer’s Weblog

programming, DSP, math

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

Advertisements

Written by pizer

March 25, 2009 at 1:56 pm

One Response

Subscribe to comments with RSS.

  1. You’re not the first to bitten by that rule: Andrei Alexandrescu was also initially ignorant of it (as were all initial reviewers, including me) when, long ago, he developed the Mojo mini-framework for DIY return value optimization. I can’t recall who it was who saw the problem, but anyway, Andrei then had to work around it. By the way, this has implications for std::auto_ptr usage in C++0x (happily std::auto_ptr is deprecated in C++0x, IIRC). Cheers, – Alf

    Alf P. Steinbach

    May 19, 2010 at 3:59 pm


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: