vc2010中的c++11特性探索

本文深入探讨C++中右值引用的概念及其应用,通过具体代码示例展示了移动语义如何提高程序效率,包括工厂模式的实现、lambda表达式的使用以及右值引用在构造函数和赋值运算符中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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/archive/2012/07/06/2578664.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值