C++ STL 容器和就地构造 [英] C++ STL container and in-place construction

查看:51
本文介绍了C++ STL 容器和就地构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下事项:

class CMyClass
{
public:
  CMyClass()
  {
    printf( "Constructor\n" );
  }
  CMyClass( const CMyClass& )
  {
    printf( "Copy constructor\n" );
  }
};

int main()
{
  std::list<CMyClass> listMyClass;

  listMyClass.resize( 1 );

  return 0;
}

它产生以下输出:

构造函数

复制构造函数

现在我的问题是:如何避免复制构造函数?或者换句话说:如何在没有不必要的复制操作的情况下在 STL 容器内创建对象.有没有办法做一个就地"?使用默认构造函数构造?

Now my question is: How do I avoid the copy constructor? Or to put it in another way: How can I create objects inside an STL container without the unnecessary copy operation. Is there some way to do an "in-place" construction using the default constructor?

更新 - 目前的答案:

Update - answers so far:

  1. 这是不可能的
  2. 使用指针或智能指针

智能指针对我的应用程序来说太过分了.但我真的想知道为什么不能这样做.想要做的事情似乎很明显.还有其他想法吗?如果它有效,我什至会接受一个讨厌的黑客......

Smart pointers are an overkill for my application. But I really wonder why this can't be done. It seems like such an obvious thing to want to do. Any other ideas? I will even accept a nasty hack if it works...

解决方案

我想我刚刚从这里提出的所有评论和答案中找到了解决我的问题的方法.解决方案是构造一个空对象并保留它,以便以后使用它来制作干净的副本.然后您可以使用其中一种获取引用的方法(如 push_back 或 insert).这仍然为每个插入的新对象调用复制构造函数,但至少它不是默认构造函数和复制构造函数:

I think I just found a solution for my problem from all the comments and answers posed here. The solution is to construct an empty object and to keep it around for the sole purpose of using it later for making clean copies of. Then you can use one of the methods that take a reference (like push_back or insert). This still calls the copy constructor for every new object inserted, but at least it is not both the default constructor AND copy constructor:

int main()
{
  CMyClass Empty;

  std::list<CMyClass> listMyClass;

  for ( int c=0; c<10; ++c )
  {
    listMyClass.push_back( Empty );
  }

  return 0;
}

推荐答案

按照设计,所有 C++ 标准库容器都存储副本.因此,如果您希望将值存储在容器中,则无法避免对复制构造函数的调用 - 唯一的出路是存储指针.如果您想减轻复制的开销,请研究使用引用计数.

By design, all the C++ Standard Library containers store copies. Therefore the call to the copy constructor cannot be avoided if you wish to store values in the container - the only way out is to store pointers instead. If you want to mitigate the overhead of copying, investigate the use of reference counting.

这篇关于C++ STL 容器和就地构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆