可能的重复:
构造函数调用机制 https://stackoverflow.com/questions/4283576/constructor-invocation-mechanism
为什么使用空括号调用不带参数的构造函数会出错? https://stackoverflow.com/questions/180172/why-is-it-an-error-to-use-an-empty-set-of-brackets-to-call-a-constructor-with-no
为什么可以这样code http://ideone.com/EogJD删除 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());
}
这段代码显然没有复制A
,并且在 ideone 的 gcc 3.4 下不输出任何内容。
问题不在于复制省略,而在于声明的含义:
B b(A());
// To get it working the way you expect [1]
B b = B(A());
// Or the slightly more obtuse.
B b((A()));
对于编译器来说是一个函数声明。谷歌/搜索SO最令人烦恼的解析。更多内容在C++ 常见问题精简版 http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.21包括解决方法。
[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_) {}
};
那么这将不是一个替代方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)