C++ 11
C++ 11
auto
auto a; // wrong
auto i = 1;
auto d = 1.0;
auto str = "Hello World";
auto ch = 'A';
auto func = less<int>();
vector<int> iv;
auto ite = iv.begin();
auto p = new foo() // customized type
initialization
int arr[3]{1, 2, 3};
vector<int> v{1, 2, 3};
map<int, string> m{{1, "a"}, {2, "b"}};
string str{"Hello World"};
for loop
map<string, int> m{{"a", 1}, {"b", 2}, {"c", 3}};
for (auto p : m){
cout<<p.first<<" : "<<p.second<<endl;
}
tuple (variable-length template)
auto p = make_pair(1, "before C++ 11");
auto t1 = make_tuple(1, 2.0, "C++ 11");
auto t2 = make_tuple(1, 2.0, "C++ 11", {1, 0, 2});
lambda expression
vector<int> iv{5, 4, 3, 2, 1};
int a = 2, b = 1;
// syntax: [global param](func args)->return_type{func body}
for_each(iv.begin(), iv.end(), [b](int &x){cout<<(x + b)<<endl;});
for_each(iv.begin(), iv.end(), [=](int &x){x *= (a + b);});
for_each(iv.begin(), iv.end(), [=](int &x)->int{return x * (a + b);});
decltype
template <typename Creator>
auto processProduct(const Creator& creator) ->
decltype(creator.makeObject()) {
auto val = creator.makeObject();
// do something with val
}
nullptr
void F(int a){
cout << a << endl;
}
void F(int *p){
assert(p != NULL);
cout << p << endl;
}
int main(){
int *p = nullptr;
int *q = NULL;
int a = nullptr; // compilation error; not allowed
bool equal = ( p == q ); // true
F(0); // compilation error in C++98 due to ambiguity; call F(int) in C++11
F(nullptr);
return 0;
}
rvalue reference; move semantics; perfect forwarding
#include <iostream>
#include <utility>
void reference(int& v) {
std::cout << "lvalue" << std::endl;
}
void reference(int&& v) {
std::cout << "rvalue" << std::endl;
}
template <typename T>
void pass(T&& v) {
std::cout << "regular: ";
reference(v);
std::cout << "std::move: ";
reference(std::move(v));
std::cout << "std::forward: ";
reference(std::forward<T>(v)); // cf. static_cast<T&&>(v)
}
int main() {
std::cout << "pass rvalue:" << std::endl;
pass(1);
std::cout << "pass lvalue:" << std::endl;
int v = 1;
pass(v);
return 0;
}
/* Output:
pass rvalue:
regular: lvalue
std::move: rvalue
std::forward: rvalue
pass lvalue:
regular: lvalue
std::move: rvalue
std::forward: lvalue
*/
Last updated