为什么复制构造函数在通过const引用传递临时时被调用? [英] why copy constructor is called when passing temporary by const reference?

查看:132
本文介绍了为什么复制构造函数在通过const引用传递临时时被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递一个未命名的临时对象到使用const ref参数定义的函数。类的复制ctor是私有的,我得到编译错误。我不明白为什么在这种情况下调用复制构造函数。

  class A {
public:
A(int i){}
private:
A(const A&){}
};

void f(const A& a)
{
}

int main()
{
f 1)); //< - error here:'A :: A(const A&)'is private
}


b $ b

正如预期的那样,当我将主要更改为:

  A a 
f(a);

它可以工作。



编译器是gcc 4.1.2

解决方案

你可以在使用临时对象复制构造函数。或直接转到 http://gcc.gnu.org/bugs/#cxx%5Frvalbind


C ++标准说,应该在这个
上下文中创建一个临时的
对象,并且它的内容填充一个
对象的副本,我们试图将
绑定到引用;它还说,
临时副本可以省略,
但是复制构造函数
的语义约束(例如
可访问性)仍然需要检查。

有关更多信息,可以参考
的以下段落:
C ++标准:[dcl.init.ref] / 5,
bullet 2 ,子项目1和
[class.temporary] / 2。



从GCC 4.3.0开始,GCC不再
这种情况下的错误。这个
的改变是基于
C ++语言委员会的意图。从
2010-05-28,最终提议的草案
的C ++ 0x标准允许这个
代码没有错误。



I am passing an unnamed temporary object to a function defined with const ref parameter. The copy ctor of the class is private, and I get a compilation error. I don't understand why a copy constructor is called in this situation.

class A {
public:
  A(int i) {}
private:
  A(const A&) {}
};

void f(const A& a)
{
}

int main()
{
  f(A(1)); // <-- error here: 'A::A(const A&)' is private
}

As expected, when I change the main to:

A a(1);
f(a);

it works.

EDIT: the compiler is gcc 4.1.2

解决方案

You can find the answer to your question in Copy Constructor Needed with temp object. or go directly to http://gcc.gnu.org/bugs/#cxx%5Frvalbind

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.

这篇关于为什么复制构造函数在通过const引用传递临时时被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆