小步慢跑

 

GCC4.1.2 中 临时对象作为参数传递给 const T& 编译报错

Copy constructor access check while initializing a reference.

Consider this code:

class A 
{
public:
  A();

private:
  A(const A&);   // private copy ctor
};

A makeA(void);
void foo(const A&);

void bar(void)
{
  foo(A());       // error, copy ctor is not accessible
  foo(makeA());   // error, copy ctor is not accessible

  A a1;
  foo(a1);        // OK, a1 is a lvalue
}

Starting with GCC 3.4.0, binding an rvalue to a const reference requires an accessible copy constructor. This might be surprising at first sight, especially since most popular compilers do not correctly implement this rule.

The C++ Standard says that a temporary object should be created in this context and its contents filled with a copy of the object we are trying to bind to the reference; it also says that the temporary copy can be elided, but the semantic constraints (eg. accessibility) of the copy constructor still have to be checked.

For further information, you can consult the following paragraphs of the C++ standard: [dcl.init.ref]/5, bullet 2, sub-bullet 1, and [class.temporary]/2.

Starting with GCC 4.3.0, GCC no longer gives an error for this case. This change is based on the intent of the C++ language committee. As of 2010-05-28, the final proposed draft of the C++0x standard permits this code without error.

posted on 2013-10-30 16:38 zaccheo 阅读(579) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

统计

常用链接

留言簿

随笔分类(23)

随笔档案(26)

文章分类(1)

文章档案(1)

csdn

搜索

最新评论

阅读排行榜

评论排行榜