Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 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()
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement