为什么这段代码可以删除副本? [英] Why can this code elide a copy?
问题描述
可能的重复项:
构造函数调用机制
为什么使用一组空括号来调用没有参数的构造函数是一个错误?
为什么可以代码删除A的所有副本?
#include< iostream&
class A
{
public:
A(){}
A(const A&){std :: cout< 复制<< std :: endl; }
};
class B
{
public:
B(const A& a_):a(a_){}
private:
一个;
};
int main()
{
B b(A());
}
这段代码显然没有复制 A <
问题不是复制elision,的声明:
B b(A());
//让它按你期望的方式工作[1]
B b = B(A());
//或稍微更钝。
B b((A()));
编译器是一个函数声明。 Google / search SO为最烦躁的解析。 C ++常见问题解答中的更多内容,包括解决方法。 p>
[1] :这不是完全一样这需要从 A
到 B
的隐式转换。如果 B
定义为:
B类{
A a;
public:
explicit B(const A& a_):a(a_){}
};
那么这将不是一个替代方案。
Possible Duplicates:
constructor invocation mechanism
Why is it an error to use an empty set of brackets to call a constructor with no arguments?
Why can this code elide all copies of A?
#include <iostream>
class A
{
public:
A() {}
A(const A&) { std::cout << "Copy" << std::endl; }
};
class B
{
public:
B(const A& a_) : a(a_) {}
private:
A a;
};
int main()
{
B b(A());
}
This code apparently makes no copies of A
, and outputs nothing under gcc 3.4 at ideone.
The problem is not copy elision, but the meaning of the declaration:
B b(A());
// To get it working the way you expect [1]
B b = B(A());
// Or the slightly more obtuse.
B b((A()));
To the compiler is a function declaration. Google / search SO for the most-vexing-parse. More in the C++ FAQ lite including workarounds.
[1]: This is not exactly the same, as this requires an implicit conversion from A
to B
. If B
was defined as:
class B {
A a;
public:
explicit B(const A& a_) : a(a_) {}
};
Then this would not be an alternative.
这篇关于为什么这段代码可以删除副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!