c++ - Create a map of objects without destroingthe objects -


this question has answer here:

i trying create map contains objects different arguments.

but found after inserting pair, object destroyed.

if try use function in object.for example:

#include <map> #include <iostream>  class test{     public:         test(double value) : value_(value){}         ~test(){std::cout<< "destroyed";}         void plusone()  {value_ += 1;}     private:         double value_; };  int main(){     std::map<long, test> map;      map.insert(std::make_pair(1, test(1.2)));     map[1].plusone();     return 0; } 

it show: [error] no matching function call 'class::class()'

[note] candidate expects 1 argument, 0 provided

how can this?

the syntax map[1] can used when mapped type has default constructor. because if key not found default-constructed object inserted, compiler has generate code @ compile-time.

if not want add default constructor have use different lookup code, e.g.:

auto = map.find(1); if ( != map.end() )     it->second.memberfuncion(); 

also, error message has nothing destroying objects, title mentions.


in code map.insert(std::make_pair(1, class(argument)));, create temporary object class(argument), , copy map. temporary object destroyed.

if want avoid , construct directly in map, use map.emplace(1, argument);.


Comments

Popular posts from this blog

gridview - Yii2 DataPorivider $totalSum for a column -

java - Suppress Jboss version details from HTTP error response -

Sass watch command compiles .scss files before full sftp upload -