C++11 initialize map - c++

I am trying to initialize a STL map using C++11 syntax but that doesn't seem to work. After initialization, when i try to access the element, it tries to call the private constructor of Foo. Did I miss something? It works if I use at. I am wondering if I could use operator[] to access initialized values...
#include <map>
#include <string>
class Foo{
public:
int a, b;
Foo(int a_, int b_){
a = a_;
b = b_;
}
private:
Foo(){};
};
int main(){
std::map<std::string, Foo> myMap = { {"1", Foo(10,5)}, {"2", Foo(5,10)} };
int b = myMap["1"].b; // it tries to call private constructor of Foo.
return 0;
}

When you use the operator[] on a map, you may use the operator to either get a value from the map or assign a value into the map. In order to assign the value into the map, the map has to construct an object of its value type, and return it by reference, so that you can use operator= to overwrite an existing object.
Consequently, the type has to be default constructible so that a new object can be created for you to assign into.
At run time, the constructor won't be called if the key already exists, but the compiler has no way of knowing whether you'll ever use operator[] to access a value that doesn't exist, so it requires the constructor to be public.

operator[] of map requires the type to be default constructible, because it creates a new entry if one doesn't exist.
You can use at() instead, which throws if the entry doesn't exist:
int b = myMap.at("1").b;

Related

Assigning of unordered_map to pair of objects

I am trying to understand the unordered_map assignment, I get the following error: no matching function for call to std::pair<foo, foo>::pair(), according to the doc for unordered_map operator[]:
If k does not match the key of any element in the container, the function inserts a new element with that key and returns a reference to its mapped value.
So I am trying to assign an object (from make_pair) to this reference, which I am guessing is not allowed. However with the pair<int,int>, it works, then I am wondering if I must declare some other operators for foo to make this work.
#include <bits/stdc++.h>
using namespace std;
struct foo {
int n;
foo(int n): n(n) {};
};
int main(){
unordered_map<int, pair<foo,foo>> m;
//m[3] = make_pair(foo(1),foo(2)); <--- error here
unordered_map<int, pair<int,int>> ii;
ii[3] = make_pair(1,2);
}
The problem is that operator [] might have to construct a value object, in your case std::pair<foo, foo>. Since foo doesn't have a default constructor, it can't construct the default std::pair.
You can either provide a default constructor for foo (including adding a default value for n), or you'll have to use another method to insert values into m.

Accessing map of class A from class B

I have two classes class A and class B. Class A has a map of type map<int,int>.
In class A, i have the following definition,
typedef std::map<int, int> mymap;
mymap MYMAP;
A A_OBJ;
// did some insert operations on A_OBJ's MYMAP
I also have the following function in class A that when invoked by B will return A's MYMAP as a copy to class B.
A::mymap A::get_port(){
// Returns A's map
return this -> MYMAP;
}
In class B,
void B::initialize_table(){
A::mymap port_table = A_OBJ.get_port();
cout<< "size of ports table at A is"<<port_table.size());
}
Code got compiled with out any issue. The only problem is that even if I insert some data to A's map, B always shows that A's map has 0 elements.
I have a timer at B which calls initialize_table() every 2s and it is supposed to get the latest copy of the map from A. Not sure where it went wrong.
Any help is appreciated. Thanks.
You're correct that you're creating a copy of the std::map. The way to fix this is by initializing a reference to the map.
Consider the following stub:
#include <iostream>
#include <map>
using my_map = std::map<int, int>;
struct A {
A() : m() {}
my_map& get_my_map() { return m; }
my_map m;
};
struct B {
B() : a() {}
void initialize_map_ref();
void initialize_map_val();
void print_index_42() { std::cout << a.get_my_map()[42] << '\n'; }
A a;
};
void B::initialize_map_ref() {
// notice this is a reference
my_map& m = a.get_my_map();
m[42] = 43;
}
void B::initialize_map_val() {
// notice this is a copy
my_map m = a.get_my_map();
m[42] = 43;
}
int main() {
B b;
b.initialize_map_ref();
b.print_index_42();
return 0;
}
B::initialize_map_ref initializes a reference (i.e., a reference to the map within a), where B::initialize_map_val creates a copy and initializes the copy. The copy dies after the call, so outside of the call, m[42] == 0. The reference initialization, on the other hand, persists because you've changed a reference to the underlying object.
Ideone: With reference and with value.
I suggest returning by an R-value reference for the sake of efficiency (i.e. A::mymap&& A::get_port(){return A::mymap(this -> MYMAP;) };).
I can only see your code failing in one of two circumstances:
you are updating A_OBJ.MYMAP after you call A_OBJ.get_port()
This will cause the copy to be out of date.
or you are updating A_OBJ.get_port(). and then calling A_OBJ.get_port() again. This will cause the copy to be modified but the original map, to be left unmodified, resulting in the second call to A_OBJ.get_port() to not consider any changes made to the value returned by the previous.
Depending on what you want you may want to return a (const) reference to the map.
EDIT I mistakenly originally thought that A::mymap port_table = A_OBJ.get_port(); would cause two copies, but now I realize it will cause a copy and then a move, it would also do that in the rvalue case, however that is likely to introduce undefined behaviour (I think) because of returning a reference to a temporary... (originally I had it return this -> MYMAP but would be an error as it would try to bind an lvalue (this -> MYMAP) to an rvalue reference)

Why can the compiler not detect the constructor? [duplicate]

I'm getting the error:
error: no matching function for call to 'A::A()'
note: candidates are: A::A(const A&)
note: A::A(const std::string&, size_t)
From this:
#include <map>
#include <string>
using std::map;
using std::string;
class A {
public:
string path;
size_t size;
A (const string& p, size_t s) : path(p), size(s) { }
A (const A& f) : path(f.path), size(f.size) { }
A& operator=(const A& rhs) {
path = rhs.path;
size = rhs.size;
return *this;
}
};
int main(int argc, char **argv)
{
map<string, A> mymap;
A a("world", 1);
mymap["hello"] = a; // <----- here
A b(mymap["hello"]); // <----- and here
}
Please tell me why the code wants a constructor with no parameters.
Because map requires DefaultConstructible values, since when using subscript operator and the key is not found it adds it mapped to a default constructed value.
In general a default constructor is not required for a map item value.
It was required in C++03, but that requirement was dropped in C++11, which often instead of posing container-wide requirements uses a more fine grained requirement scheme with requirements on the use of particular member functions.
The map::operator[] is one such member function, because it will create an item with the given key and a default-constructed value, if an item with the key doesn't exist.
This is also the reason why there isn't a const version of map::operator[]: it potentially modifies the map.
In C++11 and later you can use the at accessor to access an item with a given key in a const map, without the verbosity & complexity of a find.
Since map::at doesn't attempt to create an item, it doesn't require the item type to be default constructible.
And so one practical solution for your problem is to use map::at instead of map::operator[].
mymap["hello"] can attempt to create a value-initialized A, so a default constructor is required.
If you're using a type T as a map value (and plan to access value via operator[]), it needs to be default-constructible - i.e. you need a parameter-less (default) constructor. operator[] on a map will value-initialize the mapped value if a value with the key provided is not found.
Long time without using C++, but If I recall correctly if you don't define a constructor for a class the compiler will create a paramless one for you. As soon as you define a constructor with parameters the compiler won't create a paramless one for you, so, you are required to create one. This added to what K-ballo exposed leads to your errors.

Why is a default constructor required when storing in a map?

I'm getting the error:
error: no matching function for call to 'A::A()'
note: candidates are: A::A(const A&)
note: A::A(const std::string&, size_t)
From this:
#include <map>
#include <string>
using std::map;
using std::string;
class A {
public:
string path;
size_t size;
A (const string& p, size_t s) : path(p), size(s) { }
A (const A& f) : path(f.path), size(f.size) { }
A& operator=(const A& rhs) {
path = rhs.path;
size = rhs.size;
return *this;
}
};
int main(int argc, char **argv)
{
map<string, A> mymap;
A a("world", 1);
mymap["hello"] = a; // <----- here
A b(mymap["hello"]); // <----- and here
}
Please tell me why the code wants a constructor with no parameters.
Because map requires DefaultConstructible values, since when using subscript operator and the key is not found it adds it mapped to a default constructed value.
In general a default constructor is not required for a map item value.
It was required in C++03, but that requirement was dropped in C++11, which often instead of posing container-wide requirements uses a more fine grained requirement scheme with requirements on the use of particular member functions.
The map::operator[] is one such member function, because it will create an item with the given key and a default-constructed value, if an item with the key doesn't exist.
This is also the reason why there isn't a const version of map::operator[]: it potentially modifies the map.
In C++11 and later you can use the at accessor to access an item with a given key in a const map, without the verbosity & complexity of a find.
Since map::at doesn't attempt to create an item, it doesn't require the item type to be default constructible.
And so one practical solution for your problem is to use map::at instead of map::operator[].
mymap["hello"] can attempt to create a value-initialized A, so a default constructor is required.
If you're using a type T as a map value (and plan to access value via operator[]), it needs to be default-constructible - i.e. you need a parameter-less (default) constructor. operator[] on a map will value-initialize the mapped value if a value with the key provided is not found.
Long time without using C++, but If I recall correctly if you don't define a constructor for a class the compiler will create a paramless one for you. As soon as you define a constructor with parameters the compiler won't create a paramless one for you, so, you are required to create one. This added to what K-ballo exposed leads to your errors.

Using a class with const data members in a vector

Given a class like this:
class Foo
{
const int a;
};
Is it possible to put that class in a vector? When I try, my compiler tells me it can't use the default assignment operator. I try to write my own, but googling around tells me that it's impossible to write an assignment operator for a class with const data members. One post I found said that "if you made [the data member] const that means you don't want assignment to happen in the first place." This makes sense. I've written a class with const data members, and I never intended on using assignment on it, but apparently I need assignment to put it in a vector. Is there a way around this that still preserves const-correctness?
I've written a class with const data members, and I never intended on using assignment on it, but apparently I need assignment to put it in a vector. Is there a way around this that still preserves const-correctness?
You have to ask whether the following constraint still holds
a = b;
/* a is now equivalent to b */
If this constraint is not true for a and b being of type Foo (you have to define the semantics of what "equivalent" means!), then you just cannot put Foo into a Standard container. For example, auto_ptr cannot be put into Standard containers because it violates that requirement.
If you can say about your type that it satisfies this constraint (for example if the const member does not in any way participate to the value of your object, but then consider making it a static data member anyway), then you can write your own assignment operator
class Foo
{
const int a;
public:
Foo &operator=(Foo const& f) {
/* don't assign to "a" */
return *this;
}
};
But think twice!. To me, it looks like that your type does not satisfy the constraint!
Use a vector of pointers std::vector<Foo *>. If you want to avoid the hassle of cleaning up after yourself, use boost::ptr_vector.
Edit: My initial stab during my coffee break, static const int a; won't work for the use case the OP has in mind, which the initial comments confirm, so I'm rewriting and expanding my answer.
Most of the time, when I want to make an element of a class constant, it's a constant whose value is constant for all time and across all instances of the class. In that case, I use a static const variable:
class Foo
{
public:
static const int a;
};
Those don't need to be copied among instances, so if it applied, that would fix your assignment problem. Unfortunately, the OP has indicated that this won't work for the case the OP has in mind.
If you want to create a read-only value that clients can't modify, you can make it a private member variable and only expose it via a const getter method, as another post on this thread indicates:
class Foo
{
public:
int get_a() const { return a; }
private:
int a;
};
The difference between this and
class Foo
{
public:
const int a;
};
is:
The const int gives you assurance that not even the implementation of the class will be able to muck with the value of a during the lifetime of the object. This means that assignment rightfully won't work, since that would be trying to modify the value of a after the object's been created. (This is why, btw, writing a custom operator=() that skips the copy of a is probably a bad idea design-wise.)
The access is different – you have to go through a getter rather than accessing the member directly.
In practice, when choosing between the two, I use read-only members. Doing so probably means you'll be able to replace the value of an object with the value of another object without violating semantics at all. Let's see how it would work in your case.
Consider your Grid object, with a width and height. When you initially create the vector, and let's say you reserve some initial space using vector::reserve(), your vector will be populated with initial default-initialized (i.e. empty) Grids. When you go to assign to a particular position in the vector, or push a Grid onto the end of the vector, you replace the value of the object at that position with a Grid that has actual stuff. But you may be OK with this! If the reason you wanted width and height to be constant is really to ensure consistency between width and height and the rest of the contents of your Grid object, and you've verified that it doesn't matter whether width and height are replaced before or after other elements of Grid are replaced, then this assignment should be safe because by the end of the assignment, the entire contents of the instance will have been replaced and you'll be back in a consistent state. (If the lack of atomicity of the default assignment was a problem, you could probably get around this by implementing your own assignment operator which used a copy constructor and a swap() operation.)
In summary, what you gain by using read-only getters is the ability to use the objects in a vector or any container with value semantics. However, it then falls to you to ensure that none of Grid's internal operations (or the operations of friends of Grid) violate this consistency, because the compiler won't be locking down the width and height for you. This goes for default construction, copy construction, and assignment as well.
I'm considering making the data member non-const, but private and only accessible by a get function, like this:
class Foo
{
private:
int a;
public:
int getA() const {return a;}
};
Is this 'as good' as const? Does it have any disadvantages?
As of c++20, using const member variables are legal without restrictions that had made it virtually unusable in containers. You still have to define a copy assignment member function because it continues to be automatically deleted when a const object exists in the class. However, changes to "basic.life" now allow changing const sub-objects and c++ provides rather convenient functions for doing this. Here's a description of why the change was made:
The following code shows how to define a copy assignment member function which is useable in any class containing const member objects and uses the new functions std::destroy_at and std::construct_at to fulfil the requirement so the new "basic.life" rules. The code demonstrates assignment of vectors as well as sorting vectors with const elements.
Compiler explorer using MSVC, GCC, CLANG https://godbolt.org/z/McfcaMWqj
#include <memory>
#include <vector>
#include <iostream>
#include <algorithm>
class Foo
{
public:
const int a;
Foo& operator=(const Foo& arg) {
if (this != &arg)
{
std::destroy_at(this);
std::construct_at(this, arg);
}
return *this;
}
};
int main()
{
std::vector<Foo> v;
v.push_back({ 2 });
v.push_back({ 1 });
v.insert(v.begin() + 1, Foo{ 0 });
std::vector<Foo> v2;
v2 = v;
std::sort(v2.begin(), v2.end(), [](auto p1, auto p2) {return p1.a < p2.a; });
for (auto& x : v2)
std::cout << x.a << '\n';
}