I was experimenting with using std::map::emplace()
instead of insert. I have a simple test program below:
#include <iostream>
#include <map>
#include <string>
class CTest
{
public:
CTest() : Value(0), Name() { std::cout << "Default constructor" << std::endl; };
CTest(int val, const std::string &name) : Value(val), Name(name) {
std::cout << "Parameterized constructor" << std::endl; }
CTest(const CTest& test) {
Value = test.Value; Name = test.Name; std::cout << "Copy Constructor" << std::endl; }
CTest(CTest&& test) noexcept {
Value = test.Value; Name = test.Name; std::cout << "Move Constructor" << std::endl; }
CTest& operator=(const CTest& test) {
Value = test.Value; Name = test.Name; std::cout << "Copy assignment" << std::endl; return *this; }
CTest& operator=(CTest &&test) noexcept {
Value = test.Value; Name = test.Name; std::cout << "Move assignment" << std::endl; return *this; }
~CTest() { std::cout << "Destructor" << std::endl; }
private:
int Value;
std::string Name;
};
int main()
{
CTest t1(1, "hello");
CTest t2(2, "hello");
std::map<int, CTest> testMap;
testMap[1] = t1; //1
testMap.emplace(2, t2); //2
testMap.emplace(3, CTest(3, "hello")); //3
testMap.emplace(std::piecewise_construct, std::forward_as_tuple(4), std::forward_as_tuple(4, "hello")); //4
testMap.emplace(std::piecewise_construct, std::forward_as_tuple(4), std::forward_as_tuple(std::move(t1))); //5
return 0;
}
The output for each one is:
1
Default constructor
Copy assignment
2
Copy Constructor
3
Parameterized constructor
Move constructor
Destructor
4
Parameterized constructor
5
Move constructor
Destructor
1 involves the most copying: create an entry in the map with the default constructor, followed by copy assignment. I was surprised to see a destructor call for 3 and 5. In both cases the value passed is an rvalue. So is a temporary created from the rvalue passed in, which is deleted after use? This begs question what's the right way to use emplace? Should you just pass the arguments of the constructor, like in 4? That's best in performance as my results show.