如何使用类初始化STL向量/列表,而不调用复制构造函数

如何使用类初始化STL向量/列表,而不调用复制构造函数

问题描述:

我有一个C ++程序,它使用包含类的实例的std :: list。如果我致电 myList.push_back(MyClass(variable)); 它通过创建一个临时变量的过程,然后立即将其复制到向量,然后删除临时变量。

I have a C++ program that uses a std::list containing instances of a class. If I call e.g. myList.push_back(MyClass(variable)); it goes through the process of creating a temporary variable, and then immediately copies it to the vector, and afterwards deletes the temporary variable. This is not nearly as efficient as I want, and sucks when you need a deep copy.

我想拥有我的类的构造函数,新的的东西,而不必实现一个复制构造函数只是为了第二次分配我的内存和浪费运行时。我也不想立即从向量/列表中找到类实例,然后手动分配内存(或做一些可怕的分配在复制构造函数本身的内存)。

I would love to have the constructor of my class new something and not have to implement a copy constructor just to allocate my memory for the second time and waste runtime. I'd also rather not have to immediately find the class instance from the vector/list and then manually allocate the memory (or do something horrible like allocate the memory in the copy constructor itself).

有没有办法解决这个问题(我不使用Visual Studio BTW)?

Is there any way around this (I'm not using Visual Studio BTW)?

0x move constructors是一个部分解决方法:而不是被调用的复制构造函数,move构造函数将是。

C++0x move constructors are a partial workaround: instead of the copy constructor being invoked, the move constructor would be. The move constructor is like the copy constructor except it's allowed to invalidate the source argument.

C ++ 0x加入了另一个 你想要的: emplace_back 。 (N3092§23.2.3)你传递它的参数到构造函数,然后它调用构造函数与那些参数 ...

C++0x adds another feature which would do exactly what you want: emplace_back. (N3092 §23.2.3) You pass it the arguments to the constructor, then it calls the constructor with those arguments (by ... and forwarding) so no other constructor can ever be invoked.

对于C ++ 03,你唯一的选择是在你的类中添加一个未初始化的状态。在 push_back 后立即调用的另一个函数中执行实际构造。 boost :: optional 可能会帮助您避免初始化类的成员,但它又需要 是可拷贝构造的。或者,如Fred所说,用最初为空的智能指针完成同样的事情。

As for C++03, your only option is to add an uninitialized state to your class. Perform actual construction in another function called immediately after push_back. boost::optional might help you avoid initializing members of the class, but it in turn requires they be copy-constructible. Or, as Fred says, accomplish the same thing with initially-empty smart pointers.