Last active
March 18, 2019 18:21
-
-
Save rene-d/4382acda51502eb5c171ec9e0ce5ce38 to your computer and use it in GitHub Desktop.
C++17 emplace demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // démonstration emplace c++11 vs. c++17 | |
| // rene-d 2019 | |
| //#include <bits/stdc++.h> | |
| #include <iostream> | |
| #include <vector> | |
| #include <unordered_map> | |
| using namespace std; | |
| struct toto | |
| { | |
| int a; | |
| explicit toto(int _a) | |
| { | |
| cout << "toto() int " << _a << endl; | |
| a = _a; | |
| } | |
| toto() | |
| { | |
| cout << "toto()" << endl; | |
| a = 1; | |
| } | |
| virtual ~toto() | |
| { | |
| cout << "~toto()" << endl; | |
| } | |
| }; | |
| void test_vector() | |
| { | |
| vector<toto> t; | |
| #if _LIBCPP_STD_VER > 14 // C++17 et suivants (constante clang++) | |
| auto &&r1 = t.emplace_back(); // auto& fonctionne aussi | |
| r1.a = 100; | |
| #else | |
| auto &&r2 = t.emplace(t.end()); | |
| r2->a = 1000; | |
| #endif | |
| for (auto &&it : t) | |
| cout << "vector " << it.a << endl; | |
| } | |
| void test_map() | |
| { | |
| unordered_map<int, toto> m; | |
| auto &&r2 = m.emplace(std::piecewise_construct, | |
| std::forward_as_tuple(20), | |
| std::forward_as_tuple()); | |
| r2.first->second.a = 200; | |
| #if _LIBCPP_STD_VER > 14 | |
| // c++17 autorise une syntaxe plus simple | |
| auto &&r3 = m.try_emplace(30); | |
| r3.first->second.a = 300; | |
| #endif | |
| for (auto &&it : m) | |
| cout << "map " << it.first << " " << it.second.a << endl; | |
| } | |
| int main() | |
| { | |
| test_vector(); | |
| cout << "---------------------------------" << endl; | |
| test_map(); | |
| } | |
| /* sortie C++11 | |
| toto() | |
| vector 1000 | |
| ~toto() | |
| --------------------------------- | |
| toto() | |
| map 20 200 | |
| ~toto() | |
| */ | |
| /* sortie C++17 | |
| toto() | |
| vector 100 | |
| ~toto() | |
| --------------------------------- | |
| toto() | |
| toto() | |
| map 30 300 | |
| map 20 200 | |
| ~toto() | |
| ~toto() | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment