gpt4 book ai didi

C++11 emplace_back on vector

转载 作者:IT老高 更新时间:2023-10-28 12:08:40 24 4
gpt4 key购买 nike

考虑以下程序:

#include <string>
#include <vector>

using namespace std;

struct T
{
int a;
double b;
string c;
};

vector<T> V;

int main()
{
V.emplace_back(42, 3.14, "foo");
}

它不起作用:

$ g++ -std=gnu++11 ./test.cpp
In file included from /usr/include/c++/4.7/x86_64-linux-gnu/bits/c++allocator.h:34:0,
from /usr/include/c++/4.7/bits/allocator.h:48,
from /usr/include/c++/4.7/string:43,
from ./test.cpp:1:
/usr/include/c++/4.7/ext/new_allocator.h: In instantiation of ‘void __gnu_cxx::new_allocator<_Tp>::construct(_Up*, _Args&& ...) [with _Up = T; _Args = {int, double, const char (&)[4]}; _Tp = T]’:
/usr/include/c++/4.7/bits/alloc_traits.h:253: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 = T; _Args = {int, double, const char (&)[4]}; _Alloc = std::allocator<T>; typename std::enable_if<std::allocator_traits<_Alloc>::__construct_helper<_Tp, _Args>::value, void>::type = void]’
/usr/include/c++/4.7/bits/alloc_traits.h:390:4: required from ‘static void std::allocator_traits<_Alloc>::construct(_Alloc&, _Tp*, _Args&& ...) [with _Tp = T; _Args = {int, double, const char (&)[4]}; _Alloc = std::allocator<T>]’
/usr/include/c++/4.7/bits/vector.tcc:97:6: required from ‘void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = {int, double, const char (&)[4]}; _Tp = T; _Alloc = std::allocator<T>]’
./test.cpp:17:32: required from here
/usr/include/c++/4.7/ext/new_allocator.h:110:4: error: no matching function for call to ‘T::T(int, double, const char [4])’
/usr/include/c++/4.7/ext/new_allocator.h:110:4: note: candidates are:
./test.cpp:6:8: note: T::T()
./test.cpp:6:8: note: candidate expects 0 arguments, 3 provided
./test.cpp:6:8: note: T::T(const T&)
./test.cpp:6:8: note: candidate expects 1 argument, 3 provided
./test.cpp:6:8: note: T::T(T&&)
./test.cpp:6:8: note: candidate expects 1 argument, 3 provided

这样做的正确方法是什么?为什么?

(也试过单双大括号)

最佳答案

您需要为该类显式定义一个 ctor:

#include <string>
#include <vector>

using namespace std;

struct T
{
int a;
double b;
string c;

T(int a, double b, string &&c)
: a(a)
, b(b)
, c(std::move(c))
{}
};

vector<T> V;

int main()
{
V.emplace_back(42, 3.14, "foo");
}

使用 emplace_back 的目的是避免创建一个临时对象,然后将其复制(或移动)到目的地。虽然也可以创建一个临时对象,然后将其传递给 emplace_back,但它(至少大部分)没有达到目的。您要做的是传递单个参数,然后让 emplace_back 使用这些参数调用 ctor 以就地创建对象。

关于C++11 emplace_back on vector<struct>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13812703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com