Re: Initialising map member without copy
On 2 mar, 13:09, Paul Brettschneider <paul.brettschnei...@yahoo.fr>
wrote:
[...]
Oh, really? Does it say anywhere that insertion via operator[]
must or should do two copies?
The standard does say that insert takes an std::pair as an
operand. That's one copy. And that it must copy this object
into the map, that's the second one.
If not, then IMHO it's a QOI rather than a design issue.
It's easy to initialise a std::pair in place without copy
(ignore the alignment issues):
#include <iostream>
#include <map>
#include <string>
class Test {
std::string x;
private:
Test &operator=(const Test &t);
Test(const Test &t) : x(t.x) { throw "Copy!\n"; };
public:
Test() : x("Some content") { std::cout << "Default!\n"; };
~Test() { std::cout << "Destroy!\n"; };
void test() { std::cout << x << "\n"; };
};
typedef std::pair<std::string, Test> pair_t;
int main()
{
char mem[sizeof(pair_t)];
pair_t &test = *(new(mem) pair_t());
test.second.test();
test.~pair_t();
return 0;
}
So I have to wonder why the gcc libraries aren't doing
something like this.
They probably are. But it doesn't help. The problem is that
the first std::pair must be constructed before you've found the
"place" where the second is to be constructed, since you need it
for the lookup.
Especially considering that std::pair is internal to the
library, so it can play all kind of dirty tricks not available
to the application.
Not a big problem here: my objects are tens to hundreds of
kB, therefore the use of a smart pointer is negligible. But
in general I don't see why you would have to use smart
pointers when there are no smarts required, or why you have
to implement a copy constructor when all you do is just
insert into and erase from a map, but never copy the map or
anything like that. Keeping copy constructors up-to-date is
tedious and error prone after all.
Your 'objects' probably are objects in the sense of OO, not values.
That's the problem. Try to figure out the difference between copyable
values and non-copyable objects.
I understand that for full use of STL you need copyable values. But I don'=
t
see why, when using only a subset, in my case insertion into and deletion
from a map, it shouldn't work with non-copyable objects. As it is, I have
to use boost::ptr_map which does much more than needed for my simple
use-case.
This is a recognized problem. The next version of the standard
implements something called move-semantics, which can be used to
implement a shallow copy when the compiler determines that the
source will immediately cease to exist. (The destructor of a
"moved" object will not be called.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34