1

Is it possible to use the unique_ptr with the map container? For example,

#include<iostream>
#include<string>
#include<map>
#include<memory>
using namespace std;

int main(){
    
    unique_ptr<map<string, int>> person;
    person = make_unique<map<string, int>>(make_pair("Tom", 34));

    cout << (*person)["Tom"] << endl;  
}
3
  • 3
    person = make_unique<map<string, int>>(map<string, int>{ { "Tom", 34 } }); would work, and will use move semantics to make it relatively efficient. Commented Jan 22, 2021 at 16:36
  • 4
    Unrelated to your question. But why do you want to use unique_ptr<map<string, int>> instead of map<string, int>? Moving a std::map won't be more expensive than moving a unique_ptr. There are only rare cases where unique_ptr<map<string, int>> could be usefull. Commented Jan 22, 2021 at 16:53
  • Yes, it is possible. What problems did you have? Does this code work? If not, how not? Commented Jan 22, 2021 at 17:19

1 Answer 1

2

How about defining:

#include<iostream>
#include<string>
#include<map>
#include<memory>
using namespace std;

int main(){
    unique_ptr<map<string, int>> person(new map<string, int>); 
    (*person)["Tom"] = 34;

    cout << (*person)["Tom"] << endl;  
}

Output is:

34

See for yourself: https://wandbox.org/permlink/CNaWMLYJTxQSfKwt .

Sign up to request clarification or add additional context in comments.

9 Comments

And what is the benefit over writing unique_ptr<map<string, int>> person = make_unique<map<string, int>>(); (*person)["Tom"] = 34;? Why do you suggest an additional map in your solution?
Wait, doesn't it just create an additional COPY of the map for no reason?
@t.niese I am quite tired today, so much so that in writing my answer I have glossed over these very fine points you make. I have modified my very flawed answer accordingly.
@Lingo yep, good job. But, if I were nitpicking, I'd still prefer std::make_unique, as it looks better than a naked new, as well as using it to set the initial value.
@Lingo Can't say I disagree :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.