unwise guy
unwise guy

Reputation: 1128

How to initialize a constant map pointer to be empty in C++?

Simple question, I just want to initialize a map to be empty, instead of being a nullptr.

 const std::map<std::string, std::string>* emptyDictionary;

I tried

const std::map<std::string, std::string>* emptyDictionary = {"", ""};

but obviously that's not right. Thanks guys.

Upvotes: 1

Views: 3754

Answers (3)

Zelix
Zelix

Reputation: 1984

The default (empty) constructor of map will create an empty map http://www.cplusplus.com/reference/stl/map/map/. Either declare the map with automatic allocation on the stack by just writing

std::map<std::string, std::string> emptyDictionary();

And send it to your function using the addres-off operator

yourfunction(&emptyDictionary);

However, if the dictionary will outlive the instance of it was created, you need to dynamically allocate it instead to avoid a call to its destructor.

const std::map<std::string, std::string>* emptyDictionary = new std::map<std::string, std::string>();

Then you dont need the address-of operator when calling your function.

yourfunction(emptyDictionary);

However, the responsibility of deallocation will then be yours. When you dont need the object any longer, you need to delete the object using the delete statement.

delete emptyDictionary;

Upvotes: 1

Arne
Arne

Reputation: 2146

const std::map<std::string, std::string>* emptyDictionary 
     = new std::map<std::string, std::string>();

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 477040

You forgot to make any map at all -- you just made a pointer! You can make the pointer point to a dynamically allocated map:

 const std::map<std::string, std::string>* emptyDictionary
     = new std::map<std::string, std::string>;

This map will be truly empty. If you add the initializer {{"", ""}}, which you may well do, then you don't actually have an empty map, but rather a map with one element which maps an empty string to an empty string.

Note that you can never modify your map through the const pointer, so it's a bit questionable why you'd want to do this.

Note also that wanton dynamic allocation is generally a poor programming style. There's almost surely a better way to do whatever you need to do, or, based on your comment, you're just grossly mis­under­stand­ing something: The best way to obtain a pointer is to take the address of an existing object:

std::map<std::string, std::string> m;
foo(&m); // pass address of m as a pointer

Upvotes: 5

Related Questions