有什么情况下,用emplace_back替换push_back是不正确的? [英] Are there any cases where it is incorrect to replace push_back with emplace_back?
问题描述
我可以用 emplace_back
替换 std :: vector :: push_back
并用C ++ 11编译器编译它?从阅读 emplace_back
引用我收集它不应该发生,但我承认我不完全得到右值引用。
emplace_back / code>: #include< vector&
struct S {
S(double){}
private:
explicit S(int){}
};
int main(){
std :: vector< S>()。push_back(0); // OK
std :: vector< S>()。emplace_back(0); //错误!
}
调用 push_back
需要将其 0
类型的类型转换为 c>。由于这是一个隐式转换,不考虑显式构造函数 S :: S(int)
, S :: S(double) code>被调用。另一方面, emplace_back
执行直接初始化,因此 S :: S(double)
和 S :: S(int)
。后者是更好的匹配,但它 private
,所以程序是不成形的。
Can I break a valid C++03 program by replacing std::vector::push_back
with emplace_back
and compiling it with C++ 11 compiler? From reading emplace_back
reference I gather it shouldn't happen, but I'll admit I don't fully get rvalue references.
解决方案 I constructed a short example that actually fails to compile when push_back
is replaced by emplace_back
:
#include <vector>
struct S {
S(double) {}
private:
explicit S(int) {}
};
int main() {
std::vector<S>().push_back(0); // OK
std::vector<S>().emplace_back(0); // error!
}
The call to push_back
needs to convert its argument 0
from type int
to type S
. Since this is an implicit conversion, the explicit constructor S::S(int)
is not considered, and S::S(double)
is called. On the other hand, emplace_back
performs direct initialization, so both S::S(double)
and S::S(int)
are considered. The latter is a better match, but it's private
, so the program is ill-formed.
这篇关于有什么情况下,用emplace_back替换push_back是不正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!