我是否认为在创建Bar
的实例时会执行2份Foo
?
struct Foo {
Foo(Bar a) {
a = a; // 2nd copy Bar performed
}
private:
Bar a;
};
Foo f(myBar); // 1st copy of Bar performed
使构造函数参数成为常量引用会将副本数减少到一个。现代编译器会检测这两个副本并为我优化吗?所以实际上,我试图优化是没有意义的,因为我已经隐含地实现了这种优化。构造函数初始化列表也会导致任何不同的结果吗?
即;
struct Foo {
Foo(const Bar& a) {
a = a; // copy made
}
private:
Bar a;
};
Foo f(myBar); // no copy made
答案 0 :(得分:3)
对于第一种情况:
struct Foo {
Foo(Bar b) {
a = b; // copy assignment operator called
}
private:
Bar a; // default ctor called
};
Foo f(myBar); // copy ctor called
对于第二种情况:
struct Foo {
Foo(const Bar& b) {
a = b; // copy assignment operator called
}
private:
Bar a; // default ctor called
};
Foo f(myBar); // nothing
您可以使用member initialize list进一步改进它。
struct Foo {
Foo(const Bar& b) : a(b) { // copy ctor called
}
private:
Bar a; // nothing
};
Foo f(myBar); // nothing
PS:我将参数名称修改为@teivaz评论。