STL列表中结构的自动初始化

Auto initialization of structure in STL list

以下向列表中添加结构的方法是否有效?

#include <list>
#include <iostream>

struct TabState
{
  TabState( int p ):
    a(p),
    b(2),
    c(55),
    d(453),
    e(25521)
  {}
  int a,b,c,d,e;
};
std::list<TabState> m_tabs;

int main(int argc, char* argv[])
{
    m_tabs.push_back(77);
    std::list<TabState>::iterator iter;

    for(iter = m_tabs.begin(); iter != m_tabs.end(); ++iter)
    {
        TabState test = *iter;
        std::cout <<
            test.a << "\n" <<
            test.b << "\n" <<
            test.c << "\n" <<
            test.d << "\n" <<
            test.e << "\n";
    }
    return 0;
}

push_back() 函数是否总是自动创建一个实例?如果是这样,它是否避免了在将结构实例推入列表之前手动创建结构实例的需要?

Is the following method of adding structures to the list valid?

我发现代码中没有任何无效内容。

Does the push_back() function always create an instance automatically?

是的。

If so, does it obviate the need to manually create a structure instance before pushing it into the list?

push_back 不,它没有。您确实需要将一个对象传递给它。那是因为 push_back 通过从函数参数复制或移动来创建新实例。这就是你实际所做的。 TabState 有一个采用 int 的非显式构造函数,因此当您将 int 传递给需要 TabStateTabState&&push_back 时,然后传递的 int 将使用该构造函数隐式转换为 TabState 。该临时对象将传递给 push_back.

然而,emplace_back直接将参数转发给构造函数,因此没有中间对象。

这里发生的只是隐式转换。

  • m_tabs.push_back 期待 TabState 或可转换为 1 的东西。
  • TabState 有一个单参数构造函数,它接受一个未标记为 explicit 的 int,这意味着它允许从 intTabState 的隐式转换。

所以 m_tabs.push_back(77) 隐式地将 int 转换为 TabState。任何需要 TabState 的函数都会发生这种情况,而不仅仅是 push_back.

您编写的代码有效且正确,但有一些评论:

使构造函数显式化。您实际上是在用 int 初始化 TabState,而不是将 int 转换为 TabState

struct TabState
{
  explicit TabState( int p ):
...
  {}
...

m_tabs.push_back(TabState(77));

除非真的真的有必要,否则不要使用std::list。使用 std::vector 代替,它在大多数情况下更有效。

您可以在 for header 中声明迭代器。或者,如果您的编译器支持 C++11,请使用基于范围的 for.

for(std::list<TabState>::iterator iter = m_tabs.begin(); iter != m_tabs.end(); ++iter)

for(const TabState& element : m_tabs)