vc2010中的c++11特性探索

#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

早上来仔细研究了下右值的作用,先定义一个类来捕获各种拷贝

class A
{
public:
    A(const string& s = ""):itsFather(s){ cout << itsFather << ": A Constructor\n";}
    A(A&& A){ cout << itsFather << ": move constructor" <<endl;}
    A& operator=(const A& a){ cout << itsFather << ": = operator" << endl;return *this;}
    ~A() { cout << itsFather << ": A Destructor\n";}
    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<<"\n\n\n\n";
    A B = getA();
    cout<<"\n\n\n\n";
    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个都没有copy。

原文地址:https://www.cnblogs.com/zhangyonghugo/p/2578664.html