#include<vector>
struct A{};
int main() {
std::vector<A>a;
a.emplace_back(0, 0);
}
用
-std=c++17
编译此代码,出现以下错误:
/usr/include/c++/13/bits/new_allocator.h:187:11: error: new initializer expression list treated as compound expression [-fpermissive]
187 | { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/13/bits/new_allocator.h:187:11: error: no matching function for call to ‘A::A(int)’
a.cpp:2:8: note: candidate: ‘constexpr A::A()’
2 | struct A{};
| ^
但是,在我为
A(int)
提供 A
后,编译器尝试调用 A::A(int, int)
:
/usr/include/c++/13/bits/new_allocator.h:187:11: error: no matching function for call to ‘A::A(int, int)’
187 | { ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
a.cpp:3:5: note: candidate: ‘A::A(int)’
3 | A(int x) {}
| ^
为什么编译器会这样?
您的初始化器太多,无法初始化
A
。根据定义, A
恰好需要零个初始值设定项,但您提供了两个。将 A
放入 vector<A>
的正确方法是:
a.emplace_back(); // zero initializers