Posts Tagged ‘noncopyable’
Surprizing C++ reference-binding rules
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