Skip to content

Instantly share code, notes, and snippets.

@arielm
Last active January 3, 2016 04:39
Show Gist options
  • Save arielm/8410914 to your computer and use it in GitHub Desktop.
Save arielm/8410914 to your computer and use it in GitHub Desktop.
Checking if object copying is taking place each time std::tie is called. The answer: TestObject is not copied. Good news, say, if we want to use std::tie for maps (with complex keys...)
#include <string>
#include <tuple>
#include <iostream>
struct TestObject
{
std::string s;
int i;
TestObject(const std::string &s, int i)
:
s(s),
i(i)
{
std::cout << "TestObject CREATED: " << s << std::endl;
}
~TestObject()
{
std::cout << "TestObject DESTROYED: " << s << std::endl;
}
bool operator<(const TestObject &rhs) const
{
return std::tie(s, i) < std::tie(rhs.s, rhs.i);
}
};
struct TestKey
{
TestObject o;
float f;
TestKey(const TestObject &o, float f)
:
o(o),
f(f)
{}
bool operator<(const TestKey &rhs) const
{
return std::tie(o, f) < std::tie(rhs.o, f);
}
};
class Test
{
public:
static void run()
{
TestKey k1(TestObject("foo", 123), 0.5f);
TestKey k2(TestObject("bar", 123), 0.5f);
if ((k1 < k2) || (k2 < k1))
{
std::cout << "!=" << std::endl;
}
else
{
std::cout << "=" << std::endl;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment