4

我正在尝试转发一些论点来进行对象的就地构造。我不太明白在关联容器中使用 emplace 背后的基本原理,或者我可能只是以错误的方式使用/思考。如果有人可以共享代码片段以供使用,那就太好了。

像 map 这样的关联容器总是存储一个类型为 pair() 的对象,并且 emplace 函数表示它将通过转发参数来调用存储的对象的构造函数(对于映射,它总是 pair )。那么即使函数具有可变参数签名,我们是否只限于提供两个参数(键、值)?

当我将 emplace 与 boost 容器一起使用之前,我可以传递如下参数:emplace(arg1, arg2,arg3,arg4) // 其中 arg2,arg3,arg4 用于构造对象,而 arg 1 是关键。

当使用新的 gcc-4.6 和 c++11 编译时,这会中断但现在我必须做类似的事情: emplace (arg1 , myobj(arg2,arg3,arg4)); // 使相同的代码工作;

所以新的 emplace 没有像 boost 这样的分段构造?我是否仅限于为 maps 提供 2 个参数,因为对将始终为其构造函数接受两个参数。

4

2 回答 2

7

So the new emplace doesn't do any piece wise construction like boost ?

What you refer to a "piece wise construction" is not what the standard refers to as piecewise construction, which is:

m.emplace(std::piecewise_construct,
          std::forward_as_tuple<A1>(arg1),
          std::forward_as_tuple<A2,A3,A4>(arg2, arg3, arg4));

This does exactly what you want, forwarding the tuples of args to the first and second pair members (but be aware that with GCC 4.6 this requires an accessible copy constructor for each argument type, see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=51183 -- this requirement is fixed for GCC 4.7 by using delegating constructors, not supported by GCC 4.6)

于 2012-12-04T01:27:48.520 回答
7

这确实是标准中的一个缺陷,它在N3178中有详细说明。

去引用,

构造 value_type 对象的唯一方法是为 Key 和 Value、一对或后跟两个元组的 piecewise_construct_t 提供恰好两个参数。最初的 emplace() 提议将允许您指定一个 Key 值,然后为 Value 指定任意数量的构造函数参数。当我们删除可变参数构造函数来配对时,这种能力就消失了

...

如果要构造对象,现状是使用piecewise_construct_t。

它被关闭为“NAD”

于 2012-12-03T19:49:57.680 回答