vc 2010におけるc++11特性探索
9648 ワード
#include <algorithm>
#include <iostream>
using namespace std;
struct W
{
W(int&, int&) {}
};
struct X
{
X(const int&, int&) {}
};
struct Y
{
Y(int&, const int&) {}
};
struct Z
{
Z(const int&, const int&) {}
};
template <typename T, typename A1, typename A2>
T* factory(A1&& a1, A2&& a2)
{
return new T(std::forward<A1>(a1), std::forward<A2>(a2));
}
int&& haha(int&& a)
{
cout<< "before haha, a is " << a <<endl;
a++;
cout<< "after haha, a is " <<a <<endl;
return std::forward<int>(a);
}
int _tmain(int argc, _TCHAR* argv[])
{
char s[]="Hello World!";
int Uppercase = 0;
for_each(s,s+sizeof(s),[&](char c)
{
if(isupper(c))
Uppercase++;
});
cout<<Uppercase << " uppercase letters in: " << s << endl;
/*
int my_array[]={1,2,3,4,5,6};
for (int& x : my_array)
{
cout << x <<endl;
}*/
auto myLambdaFunc = [](){cout<<"haha"<<endl;};
//myLambdaFunc();
int a = 4, b = 5;
W* pw = factory<W>(a, b);
X* px = factory<X>(2, b);
Y* py = factory<Y>(a, 2);
Z* pz = factory<Z>(2, 2);
delete pw;
delete px;
delete py;
delete pz;
cout << "first a is :" << a <<endl;
haha(std::forward<int>(a));
cout<< "really a is :" << a <<endl;
int c = haha(int(100));
cout << "c now is " << c <<endl;
return 0;
}
明日また見ます.
http://msdn.microsoft.com/en-us/library/dd293668.aspx
朝は右の値の役割をよく研究して、まず1つのクラスを定義して各種のコピーを捕獲します
class A
{
public:
A(const string& s = ""):itsFather(s){ cout << itsFather << ": A Constructor
";}
A(A&& A){ cout << itsFather << ": move constructor" <<endl;}
A& operator=(const A& a){ cout << itsFather << ": = operator" << endl;return *this;}
~A() { cout << itsFather << ": A Destructor
";}
string itsFather;
A(const A& a){ cout << itsFather << ": copy constructor" <<endl;}
};
さらに2つの関数を定義して、効果を比較します.
A getA()
{
A temp("GetA");
return temp;// forward<A>(temp);
}
A GetMoveA()
{
A temp("GetMoveA");
return std::move<A>(std::forward<A>(temp));
}
cout<<"
";
A B = getA();
cout<<"
";
A C = GetMoveA();
出力結果を見て、おかしいですね.
GetA: A Constructor
: move constructor
GetA: A Destructor
GetMoveA: A Constructor
: move constructor
GetMoveA: A Destructor
: A Destructor
: A Destructor
本来の方法はかえって有効になった.第2の方法は2つの一時オブジェクトのプロファイルを増やしたが,これら2つともcopyはなかった.