다음 코드 GCC 컴파일시emplace_back()이 균일 한 초기화를 사용하지 않는 이유는 무엇입니까?
#include <vector>
struct S
{
int x, y;
};
int main()
{
std::vector<S> v;
v.emplace_back(0, 0);
}
다음 에러를 제공합니다
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
가 emplace_back()
의 인수의 요소를 구성하는 일반 ()
생성자의 구문을 사용하는 것을 제안. 왜 vector
은 위와 같은 예제를 만들기 위해 {}
균일 초기화 구문을 대신 사용하지 않습니까?
{}
(하나가있을 때 생성자를 호출하지만 여전히 존재하지 않을 때 작동 함)을 사용하면 잃을 것이 아무것도없는 것처럼 보입니다. C++의 정신에 더 가까울 것입니다. 11 {}
을 사용하십시오 - 어쨌든 균일화 초기화의 전체 점은 객체를 초기화하기 위해 균일하게, 즉 어디에서나 사용된다는 것입니다.
완벽하게 구문 중괄호 init 목록을 전달하는 언어 supporrt 유형을 만들 수 있습니다. 그렇다면 그냥 emplace_back ({a, b, ...})이라고 말할 수 있습니다. –
@ JohannesSchaub-litb : IMHO, std :: initializer_list가 무엇을 가져야하는지 더 좋아합니다. 그러나'std :: allocator'를 간단하게 수정하면 문제가 해결 될 것입니다. – Potatoswatter
vvuser가 사용자 정의 alloc으로 벡터를 제거하고 emplace_back (1,2, alloc)을 작성하면 어떨까요? 그것을 ({1,2}, alloc)로 전달하는 것을 어떻게 알 수 있습니까? 할당 자 해킹이 더 많은 것을 깨뜨리는 것. 적절한 해결책을 찾아야한다. –