Re: Assignment on map
On Nov 23, 10:39 am, Andrea Crotti <andrea.crott...@gmail.com> wrote:
Andrea Crotti <andrea.crott...@gmail.com> writes:
What's wrong with this thing?
std::map<std::string, Param> int_params;
Param p(1,10);
int_params["sadf"] = p;
Where this is Param?
typedef unsigned int int_param_t;
class Param
{
private:
int_param_t min;
int_param_t max;
int_param_t value;
std::string name;
public:
Param(int_param_t _min, int_param_t _max) : min(_min), max(_max=
) {}
void set(int_param_t);
void set(const std::string&);
};
Trying to compile it says
expected constructor, destructor, or type conversion before '=' token
But why? the object is created, the map is there...
I also tried with a temporary string but it's the same.
std::map<std::string, Param> int_params;
string s("name");
Param p(1,10);
int_params[s] = p;
And by the way is there no syntax to do something like:
int_params["name"] = Param(1, 10);
Like this is not correct but I would like to avoid to create n temporary
objects to then add to the map..
Can't avoid temps. Think about it: you have one object on the stack,
and you'll have one in the map. There's always one more. The only
thing you can do is to put pointers to your objects in the map, which
is only OK if object copy construction or assignment is more expensive
then going to heap (doesn't seem to be the case here). Note that a
typical map implementation __will__ touch heap to allocate storage for
the node, so it's likely that your copy time is already swamped by
that.
So... Why would you like to avoid temps? If only because you __think__
it's slow, then forget it. You need to care only if you __know__ it's
slow. So do you? At any rate, try to measure your copying time, and
measure total map insertion/cleanup before you jump to this particular
"optimization".
Goran.