次のコード:GCCでコンパイルしたときemplace_back()が均一な初期化を使用しないのはなぜですか?
#include <vector>
struct S
{
int x, y;
};
int main()
{
std::vector<S> v;
v.emplace_back(0, 0);
}
は、次のエラーを与える:
vector
は
emplace_back()
に引数から要素を構築するために、定期的
()
コンストラクタ構文を使用していることを示唆している
In file included from c++/4.7.0/i686-pc-linux-gnu/bits/c++allocator.h:34:0,
from c++/4.7.0/bits/allocator.h:48,
from c++/4.7.0/vector:62,
from test.cpp:1:
c++/4.7.0/ext/new_allocator.h: In instantiation of 'void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = S; _Args = {int, int}; _Tp = S]':
c++/4.7.0/bits/alloc_traits.h:265:4: required from 'static typename std::enable_if<std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::value, void>::type std::allocator_traits<_Alloc>::_S_construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = S; _Args = {int, int}; _Alloc = std::allocator<S>; typename std::enable_if<std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::value, void>::type = void]'
c++/4.7.0/bits/alloc_traits.h:402:4: required from 'static void std::allocator_traits<_Alloc>::construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = S; _Args = {int, int}; _Alloc = std::allocator<S>]'
c++/4.7.0/bits/vector.tcc:97:6: required from 'void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = {int, int}; _Tp = S; _Alloc = std::allocator<S>]'
test.cpp:11:24: required from here
c++/4.7.0/ext/new_allocator.h:110:4: error: new initializer expression list treated as compound expression [-fpermissive]
c++/4.7.0/ext/new_allocator.h:110:4: error: no matching function for call to 'S::S(int)'
c++/4.7.0/ext/new_allocator.h:110:4: note: candidates are:
test.cpp:3:8: note: S::S()
test.cpp:3:8: note: candidate expects 0 arguments, 1 provided
test.cpp:3:8: note: constexpr S::S(const S&)
test.cpp:3:8: note: no known conversion for argument 1 from 'int' to 'const S&'
test.cpp:3:8: note: constexpr S::S(S&&)
test.cpp:3:8: note: no known conversion for argument 1 from 'int' to 'S&&'
。なぜ、vector
は、上記のような例を作るために、{}
均一初期化構文を代わりに使用しないのですか?
{}
(1つではコンストラクタが呼び出されますが、1つではない場合でも動作します)を使用すると失うものはないようですが、C++の精神{}
を使用する11 - つまり、どこにでも - - オブジェクトを初期化するために、すべての後、均一初期の全体のポイントは、均一に使用されることです。
構文補完のinitリストを完全に転送する言語補完型を発明できました。それでは、emplace_back({a、b、...})と言うことができます –
@ JohannesSchaub-litb:IMHO、これは 'std :: initializer_list'と同じです。しかし、 'std :: allocator'を単純に変更するだけで問題は解決します。 – Potatoswatter
vvuserがカスタムallocでベクトルを置き換えたい場合は、emplace_back(1,2、alloc)を書き込みます。それを({1,2}、alloc)として転送する方法をどのように知っていますか?アロケータのハックは、より多くの事柄を壊すことになります。適切な解決策を検討する必要があります。 –