You can use rvalues for creating move semantics - remove copy constructors for temporaries. Example:
#include <iostream>
class A
{
public:
A()
{
x = new int[1];
x[0] = 1;
std::cout << "new\n";
}
~A()
{
delete[] x;
}
A(const A& a)
{
x = new int[1];
x[0] = a.x[0];
std::cout << "new\n";
}
/* A(A&& a) //move constructor
{
x = a.x;
a.x = 0;
}*/
private:
int *x;
};
A GetA()
{
A a;
return a;
}
//if you want to use movable object as member in another object you should declare move constructor
//and use std::move
class B
{
public:
B(){}
B(B&& b) //move constructor
{
a = std::move(b.a);
}
A a;
};
B GetB()
{
B b;
return b;
}
int main(int, char*[])
{
B b = GetB();
{
A a = GetA();
A a2(a);
std::cout << "scope\n";
}
return 0;
}
четвер, 12 серпня 2010 р.
Підписатися на:
Дописи (Atom)