且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么复制构造函数在通过const引用传递临时时被调用?

更新时间:2023-11-11 23:27:40

你可以在使用临时对象复制构造函数。或直接转到 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.