Re: map inserts by reference or via copy ctor
puzzlecracker wrote:
Does map copy the object, both key and value during the insert?
Yes.
is this example correct:
std::map<std::string T> my_map;
I think you meant
std::map<std::string, T> my_map;
template<typename T>
void foo(const std::string str, const T & t){
Passing the string by value? You ought to do
void foo(const std::string & str, const T & t){
(although it doesn't make it incorrect, per se).
my_map.insert(make_pair(str, t));
'make_pair' will either create a wrong pair (the second template
argument would be a reference to const, or it will be the right pair,
but then creation of it will make the first copy. The insertion itself
will [also] make a copy since the temporary created by 'make_pair' will
be destroyed at the end of the full expression.
}
template<typename T>
void bar()
{
foo(std::string("Key1"),T(param1, param2));
Unless you have some other overload of 'foo', there is no need to spell
out the type of the first argument, there exists an implicit conversion
from a character pointer to 'std::string'. You could just write
foo("Key1", T(param1, param2));
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask