std::vector und move-semantics
Verfasst: 26.10.2012, 17:21
Wieder einmal ein wohl semi-triviales Problem von mir.
Ich habe gerade folgendes Problem: Ich habe Objekte vom Typ MyClass, welche
Code (auch wie immer in Farbe):
Wie man sieht, funktioniert das nicht mit Iteratoren; die würde ich jedoch ganz gerne verwenden (Vergleich mit einem std::find-Resultat). Alles, was ich im Internet sonst dazu gefunden habe, läuft auf std::swap hinaus, was ich (so weit ich das sehe) hier nicht benutzen kann, weil das Objekt nicht default-konstruierbar ist.
Das sieht doch schon wieder nach einem solchen Standard-Problem aus, als dass es in jedem C++-Buch stehen müsste; ich finde aber händeringend absolut nichts dazu. :|
Ich habe gerade folgendes Problem: Ich habe Objekte vom Typ MyClass, welche
- Nicht default-konstruierbar sind,
- nicht kopier-konstruierbar sind,
- nicht kopier-zuweisbar sind.
Code (auch wie immer in Farbe):
Code: Alles auswählen
#include <iostream>
#include <cassert>
#include <vector>
class MyClass
{
public:
explicit MyClass(
int theA,
int theB
) : myA(theA),
myB(theB)
{
return;
};
MyClass(
MyClass && theOther
) : myA(std::move(theOther.myA)),
myB(std::move(theOther.myB))
{
return;
}
MyClass & operator=(
MyClass && theOther
) {
assert(this != &theOther);
myA = std::move(theOther.myA);
myB = std::move(theOther.myB);
}
private:
// Not default-constructible.
explicit MyClass();
// Enforce move-semantics.
MyClass(const MyClass & theOther);
MyClass & operator=(const MyClass & theOther);
public:
int myA;
int myB;
};
int main(int argc, char * argv[])
{
std::vector<MyClass> v1;
std::vector<MyClass> v2;
v1.push_back(MyClass(1, 2));
v1.push_back(MyClass(2, 3));
v1.push_back(MyClass(2, 4));
// Works.
for(auto i = 0u; i < v1.size(); i++)
if(v1[i].myA == 2)
v2.push_back(std::move(v1[i]));
/*
// Does not work: Calls copy-constructor.
for(auto i = v1.cbegin(); i != v1.cend(); i++)
if(i->myA == 2)
v2.push_back(std::move(*i));
*/
// list1 may not be used any longer!
return 0;
}
Das sieht doch schon wieder nach einem solchen Standard-Problem aus, als dass es in jedem C++-Buch stehen müsste; ich finde aber händeringend absolut nichts dazu. :|