ghostbody / 15-cpp-learning

15 c++ learning repository of SDCS SYSU
6 stars 3 forks source link

C++11 features #15

Open ghost opened 8 years ago

ghost commented 8 years ago

C++11 features

Created by stary 颜泽鑫

This is the first time I write a article in English, so if there are some sentences which are hard to understand, I will explain in Chinese or you can send me a message. Thank you very much.

The most message is in my CSDN blog:C++11新标准特性介绍

auto

In swift, you don't need to tell compiler what type of your variable is, but in c++, before c++ 11, you need to assign a variable of special type.

In c++ 11, in order to simplify Generic Programming,you can use auto.

int main () {
    auto a = 1;
    auto b = "yan";
    cout << b << endl;
    b += a; // b被解析成一个指针char*,指向字符串的第一个地址。
    cout << b << endl;
    return 0;
}
/*output:
yan
an
*/

What is more, in templete, auto can be very useful! Assume that, you wanna design a template class to express proccess Product like this:

template <typename Product, typename Creator>
void processProduct(const Creator& creator) {
    Product* val = creator.makeObject();
    // 必须明确指出val的类型!
    ...
}

You can use auto in val so that you don't need Product typename anymore.

template <typename Creator>
void processProduct(const Creator& creator) {
    auto val = creator.makeObject();
    // creator.makeObject会返回一个Product的类型,于是就不必再指出val的类型了。
    ...
}

decltype

Otherwise, you can use auto to automatically to make an variable convert to specific type, and you can also use decltype to know what type of an auto variable is.

    auto b = "yan";
    decltype(b) c = "1";

Following the last example, if we wanna make product as return value, we write like this:

template <typename Creator>
void processProduct(const Creator& creator) -> decltype(creator.makeObject()) {
// decltype会解析出creator.makeObject的类型作为返回类型。
    auto val = creator.makeObject();
    // creator.makeObject会返回一个Product的类型,于是就不必再指出val的类型了。
    ...
}

lambda function

I have write a blog in CSDN, you can find more message in that blog. C++11:匿名函数(lambda函数/表达式)及其用法

移动复制和右值引用

[C++]右值引用和转移语义

unqiu_ptr

C++智能指针 unique_ptr

conclusion

That is what I have learned about C++ 11.