This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: Improve insert/emplace robustness to self insertion
- From: Jonathan Wakely <jwakely at redhat dot com>
- To: François Dumont <frs dot dumont at gmail dot com>
- Cc: libstdc++ at gcc dot gnu dot org
- Date: Tue, 5 Jul 2016 11:47:07 +0100
- Subject: Re: Improve insert/emplace robustness to self insertion
- Authentication-results: sourceware.org; auth=none
- References: <20160620074230.GB6159@redhat.com> <5772D70D.4020103@gmail.com> <20160629091056.GH7722@redhat.com> <577424D3.10008@gmail.com> <20160629203625.GK7722@redhat.com> <20160629213021.GN7722@redhat.com> <57757830.7040106@gmail.com> <20160701095408.GR7722@redhat.com> <57776142.6010106@gmail.com> <20160704145523.GC7722@redhat.com>
On 04/07/16 15:55 +0100, Jonathan Wakely wrote:
I'm getting nervous about the smart insertion trick to avoid making a
copy, I have a devious testcase in mind which will break with that
change. I'll share the testcase later today.
Here's a testcase which passes with libstdc++ but fails with libc++
because libc++ doesn't make a copy when inserting a T lvalue into
std::vector<T>:
#include <vector>
#include <memory>
#include <cassert>
struct T
{
T(int v = 0) : value(v) { }
T(const T& t);
T& operator=(const T& t);
void make_child() { child = std::make_unique<T>(value + 10); }
std::unique_ptr<T> child;
int value;
};
T::T(const T& t) : value(t.value)
{
if (t.child)
child.reset(new T(*t.child));
}
T& T::operator=(const T& t)
{
value = t.value;
if (t.child)
{
if (child)
*child = *t.child;
else
child.reset(new T(*t.child));
}
else
child.reset();
return *this;
}
int main()
{
std::vector<T> v;
v.reserve(3);
v.push_back(T(1));
v.back().make_child();
v.push_back(T(2));
v.back().make_child();
assert(v[1].child->value == 12);
assert(v[1].child->child == nullptr);
v.insert(v.begin(), *v[1].child);
assert(v[0].value == 12);
assert(v[0].child == nullptr);
}
The problem is that the object being inserted (*v[1].child) is not an
element of the vector, so the optimization assumes it is unchanged by
shuffling the existing elements. That assumption is wrong.
As far as I can see, this program is perfectly valid. It's slightly
contrived to prove a point, but it's not entirely unrealistic code.