Iterate map<string, unique_ptr<Foo> > - c++11

I see there exists a very close Q/A here: Iterating over a container of unique_ptr's
However when it involves iteration of map, I do not see how to avoid copy/assignment of the unique_ptr.
When I iterate the map, e.g., using c++17 for simplicity, assuming x is a public member variable of int type for Foo:
map<string, unique_ptr<Foo> > my_map;
for (auto const& [key, val] : my_map) {
val->x = 1;
}
I got the error:
constexpr std::pair<_T1, _T2>::pair(const std::pair<_T1, _T2>&) [with _T1 = const std::__cxx11::basic_string<char>; _T2 = std::unique_ptr<Foo>]’ is implicitly deleted because the default definition would be ill-formed:
I do see another post (Cannot iterate over map whose elements hold a uniq_ptr) doing:
map<string, wrapper_struct > my_map;
where wrapper_struct is a struct with unique_ptr inside. My question is: are there any simpler solutions?

You can use a const reference to the iterator itself instead of the elements in the pair.
for (const auto& it : my_map) {
auto ptr_to_unique_foo = it.second.get();
}

Related

Using coeffRef with const CwiseUnaryView - Failing when multiplying two CWiseUnaryViews

I'm having some trouble when using coeffRef() with a CWiseUnaryView function, but only when the function is declared as const
Reproducible example:
#include <Eigen/Core>
struct dummy_Op {
EIGEN_EMPTY_STRUCT_CTOR(dummy_Op)
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE const double&
operator()(const double &v) const { return v; }
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE double&
operator()(double &v) const { return v; }
};
void foo(Eigen::MatrixXd &out)
{
//Compiles
Eigen::CwiseUnaryView<dummy_Op, Eigen::MatrixXd> view(out);
view.coeffRef(0,0);
//Doesn't Compile
const Eigen::CwiseUnaryView<dummy_Op, Eigen::MatrixXd> const_view(out);
const_view.coeffRef(0,0);
}
Returns:
<source>: In function 'void foo(Eigen::MatrixXd&)':
<source>:21:28: error: passing 'const Eigen::CwiseUnaryView<dummy_Op,
Eigen::Matrix<double, -1, -1> >' as 'this' argument discards qualifiers
[-fpermissive]
const_view.coeffRef(0,0);
^
In file included from /opt/compiler-explorer/libs/eigen/v3.3.4/Eigen/Core:413,
from <source>:1:
/opt/compiler-explorer/libs/eigen/v3.3.4/Eigen/src/Core/DenseCoeffsBase.h:340:33: note:
in call to 'Eigen::DenseCoeffsBase<Derived, 1>::Scalar&
Eigen::DenseCoeffsBase<Derived, 1>::coeffRef(Eigen::Index, Eigen::Index)
[with Derived = Eigen::CwiseUnaryView<dummy_Op, Eigen::Matrix<double,
-1, -1> >; Eigen::DenseCoeffsBase<Derived, 1>::Scalar = double; Eigen::Index = long int]'
EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col)
^~~~~~~~
Compiler returned: 1
Compiler explorer: https://godbolt.org/z/kPHPuC
The side-effect of this, is that the multiplication of two (non-const) CWiseUnaryViews also fails, see example here: https://godbolt.org/z/JYQb3d
The bottom line is that you're calling a non-const method of a constant instance. The (first) coeffRef that is being called is the one (and only) in DenseCoeffsBase.h (DenseCoeffsBase<Derived, WriteAccessors>), which is not const qualified. The DenseCoeffsBase<Derived, ReadOnlyAccessors> class does not have a coeffRef method. You can get around this error (and get a warning) if you enable the -fpermissive compiler flag.
In the dense case, you probably want to use the operator()(Index, Index) method anyway, which does have a const qualified version. I just noticed the documentation explicitly says to use that method anyway, even for the non-const version. This is obviously not going to return a const reference, but at least in your example as a double, it shouldn't matter too much.
CwiseUnaryView is intended to be used for L-value like expression, e.g.,
MatrixXcd A;
A.real() = something; // `A.real()` is writable
If you want to apply an element-wise functor and use it as an R-value, you should use CwiseUnaryOp instead:
void foo(Eigen::MatrixXd &out)
{
Eigen::CwiseUnaryOp<dummy_Op, Eigen::MatrixXd> view1(out);
// shorter:
auto view2 = out.unaryExpr(dummy_Op());
Eigen::MatrixXd result = view1 * view2;
// or directly write: out.unaryExpr(dummy_Op()) * out.unaryExpr(dummy_Op());
}

C++11: Variadic template deduction logic

I have the following construct:
template <class... Args>
class some_class
{
public:
some_class() = default;
some_class(Args...) = delete;
~some_class() = default;
};
template<>
class some_class<void>
{
public:
some_class() = default;
~some_class() = default;
};
The reason for this is that I just want to allow the users to create objects using the default constructor, so for example:
some_class<int,float> b;
should work but
some_class<int,float> c(1,3.4);
should give me a compilation error.
At some point in time I also needed to create templates based on void hence, the specialization for void:
some_class<void> a;
But by mistake I have typed:
some_class<> d;
And suddenly my code stopped compiling and it gave me the error:
some_class<Args>::some_class(Args ...) [with Args = {}]’ cannot be
overloaded
some_class(Args...) = delete;
So here comes the question: I feel that I am wrong that I assume that some_class<> should be deduced to the void specialization... I just don't know why. Can please someone explain why some_class<> (ie: empty argument list) is different from some_class<void>? (A few lines from the standard will do :) )
https://ideone.com/o6u0D6
void is a type like any other (an incomplete type, to be precise). This means it can be used as a template argument for type template parameters normally. Taking your class template, these are all perfectly valid, and distinct, instantiations:
some_class<void>
some_class<void, void>
some_class<void, void, void>
some_class<void, char, void>
In the first case, the parameter pack Args has one element: void. In the second case, it has two elements: void and void. And so on.
This is quite different from the case some_class<>, in which case the parameter pack has zero elements. You can easily demonstrate this using sizeof...:
template <class... Pack>
struct Sizer
{
static constexpr size_t size = sizeof...(Pack);
};
int main()
{
std::cout << Sizer<>::size << ' ' << Sizer<void>::size << ' ' << Sizer<void, void>::size << std::endl;
}
This will output:
0 1 2
[Live example]
I can't really think of a relevant part of the standard to quote. Perhaps this (C++11 [temp.variadic] 14.5.3/1):
A template parameter pack is a template parameter that accepts zero or more template arguments. [ Example:
template<class ... Types> struct Tuple { };
Tuple<> t0; // Types contains no arguments
Tuple<int> t1; // Types contains one argument: int
Tuple<int, float> t2; // Types contains two arguments: int and float
Tuple<0> error; // error: 0 is not a type
—end example ]

How can I return char array with boost::optional

I try to return simple array with boost::optional
boost::optional<const char *> foo () {
char ar[100] = {};
return boost::make_optional(true, ar);
}
and I got the following error:
could not convert ‘boost::make_optional(bool, const T&) [with T = char [100]](ar)’ from ‘boost::optional<char [100]>’ to ‘boost::optional<const char*>’ return boost::make_optional(true, ar);
How can I handle such confusion?
Closest you can do is by using a wrapper with value semantics.
That wrapper is std::array:
boost::optional<std::array<char, 100> > foo () {
std::array<char, 100> ar {};
return boost::make_optional(true, ar);
}
About arrays vs. pointers:
How do I use arrays in C++?
boost::make_optional deduced ar as char [100] type, but it expected const char *. By default implicit casting is not happened in template parameter deduction.
If you want to use raw pointer, it is possible to use the following solution:
boost::optional<const char *> foo () {
char ar[100] = {};
return boost::make_optional(true, static_cast<const char *>(ar));
}
But in this case you lose information how many elements located in this array and maybe better to use in foo() function std::vector or std::array as in example of sehe
Good luck !!

Additional move constructor in pass by value function

I have a simple struct, that has all constructors defined.
It has an int variable, each constructor and assign operator prints address of *this, current value of int and a new value of int.
Move and copy assign operators and constructors also print adress of passed value.
#include <iostream>
struct X
{
int val;
void out(const std::string& s, int nv, const X* from = nullptr)
{
std::cout<<this<<"->"<<s<<": "<<val<<" ("<<nv<<")";
if (from)
std::cout<<", from: ["<<from<<"]";
std::cout<<"\n";
}
X(){out("simple ctor X()",0); val = 0;}
X(int v){out("int ctor X(int)", v);val = v; }
X(const X& x){out("copy ctor X(X&)", x.val, &x);val = x.val; };
X&operator = (const X& x){out("copy X::operator=()", x.val, &x); val = x.val; return *this;}
~X(){out("dtor ~X", 0);}
X&operator = (X&& x){out("move X::operator(&&)", x.val, &x); val = x.val; return *this;}
X(X&& x){out("move ctor X(&&x)", x.val, &x);val = x.val;}
};
X copy(X a){return a;}
int main(int argc, const char * argv[]) {
X loc{4};
X loc2;
std::cout<<"before copy\n";
loc2 = copy(loc);
std::cout<<"copy finish\n";
}
output:
0xffdf7278->int ctor X(int): 134523184 (4)
0xffdf727c->simple ctor X(): 134514433 (0)
before copy
0xffdf7280->copy ctor X(X&): 1433459488 (4), from: [0xffdf7278]
0xffdf7284->move ctor X(&&x): 1433437824 (4), from: [0xffdf7280]
0xffdf727c->move X::operator(&&): 0 (4), from: [0xffdf7284]
0xffdf7284->dtor ~X: 4 (0)
0xffdf7280->dtor ~X: 4 (0)
copy finish
0xffdf727c->dtor ~X: 4 (0)
0xffdf7278->dtor ~X: 4 (0)
What's the purpose of creating an additional object with (in this example) address 0xffdf7284?
If you look at the copy elision rules from cppreference.com, you can notice that there are two case where the compilers are required to omit the copy- and move- constructors of class objects even if copy/move constructor and the destructor have observable side-effects (which yours do, due to the printouts). The first is clearly irrelevant to this case. The second is
In a function call, if the operand of a return statement is a prvalue and the return type of the function is the same as the type of that prvalue.
With the example given of:
T f() { return T{}; }
T x = f();
This seems more relevant, however, note that in your case, the operand of the return statement is not a prvalue. So in this case, no mandatory elision applies.
The set of steps, when callingloc2 = copy(loc);, is as follows:
a is copy-constructed from loc.
The return value of the function is move-constructed from a.
loc2 is move-assigned from the return value.
Logically, a person could look at the code and deduce that fewer operations need to be done (in particular, when looking at copy, it's obvious that, logically, an assignment from loc to loc2 is enough), but the compiler doesn't know that the purpose of your code isn't to generate the side effects (the printouts), and it is not breaking any rules here.

const list, non-const element access

I've a problem with boost intrusive containers.
One of my classes has an intrusive list of some objects, whose lifetimes are strictly managed by it. The objects themselves are meant to be modified by the users of the class, but they are not supposed to modify the list itself. That's why I'm only providing access to the list through a "getList" function, which returns a const version of the intrusive list.
The problem with const intrusive lists is that the elements also turn out to be const when you're trying to iterate through them. But the users should be able to iterate through and modify the items.
I don't want to keep a separate list of pointers to give to the users, because that would invalidate one of the biggest advantages of using intrusive containers. Namely, the ability to remove items from the container in constant time, while the only thing you have is a pointer to the item.
It would be sad to have to give a non-const version of my list just because of a limitation of C++. So the question is: Is there a special const version of the boost intrusive containers, which magically allows item modifications while disallowing any modifications on the list itself?
You don't need to return a list, give an access to separate items by reference
OK, I've designed a complete solution to the problem. Andy's solution is nice, if you don't need to iterate over the items in an efficient manner. But I wanted something that's semantically equivalent to const std::list. Maybe it's an overkill, but performance wise there's almost no difference after optimizations:
The solution is to privately extend the intrusive list with a class called ConstList, which exposes just enough to let BOOST_FOREACH iterate, but not to make any changes by anyone. I've moved the list hook from the item to a child class, so that an item object cannot be used to change the list either. We're storing the child class with the hook, but our iterators are returning references to the item class. I've coded this solution into two templated classes for easy application to any item class.
I've made a header file with the ConstList class and the HookedItem class, followed by the tests.cpp, used to test and benchmark. You'll see that our ConstList class has equal performance while iterating.
It works quite cleanly, and the user code also stays clean. Then this begs the question: Why isn't this already in boost????!?!?
Feel free to use the following code for any purpose :)
P.S: I've had a moment of revelation while coming up with this solution: "const" is nothing but a syntactic sugar for a special case of what you can already achieve with the right class hierarchy. Is that true, or was I over-generalizing?
------------------ ConstList.h -----------------------
#include <boost/intrusive/list_hook.hpp>
template < typename T>
struct type_wrapper{ typedef T type;};
template<class listType, class owner, class item>
class ConstList: private listType {
friend class type_wrapper<owner>::type;
public:
class iterator {
typename listType::iterator it;
public:
typedef std::forward_iterator_tag iterator_category;
typedef item value_type;
typedef int difference_type;
typedef item* pointer;
typedef item& reference;
template<class T>
iterator(const T it): it(it){}
bool operator==(iterator & otherIt) {return it==otherIt.it;}
iterator & operator++() {
it++;
return *this;
}
item & operator*() {
return *it;
}
};
iterator begin() {
return iterator(listType::begin());
}
iterator end() {
return iterator(listType::end());
}
};
template<class item, class owner, class hooktype>
class HookedItem: public item {
friend class type_wrapper<owner>::type;
public:
hooktype hook_;
typedef boost::intrusive::member_hook<HookedItem, hooktype, &HookedItem::hook_> MemberHookOption;
private:
template<class Arg1, class Arg2>
HookedItem(Arg1 &arg1, Arg2 &arg2): item(arg1, arg2){}
};
------------------ tests.cpp -----------------------
#include<cstdio>
#include<boost/checked_delete.hpp>
#include<ConstList.h>
#include<boost/intrusive/list.hpp>
#include<boost/foreach.hpp>
using namespace boost::intrusive;
class myOwner;
class myItem {
public:
int a,b; //arbitrary members
myItem(int a, int b): a(a), b(b){};
};
typedef HookedItem<myItem,myOwner,list_member_hook<> > myHookedItem;
typedef list<myHookedItem, typename myHookedItem::MemberHookOption> myItemList;
typedef ConstList<myItemList,myOwner,myItem> constItemList;
class myOwner {
public:
constItemList constList;
myItemList & nonConstList;
myOwner(): nonConstList(constList) {}
constItemList & getItems() { return constList;}
myItem * generateItem(int a, int b) {
myHookedItem * newItem = new myHookedItem(a,b);
nonConstList.push_back(*newItem);
return newItem;
}
~myOwner() {nonConstList.clear_and_dispose(boost::checked_delete<myHookedItem>);}
};
int main(int argc, char **argv) {
myOwner owner;
int avoidOptimization=0;
for(int i=0; i<1000000; i++) {
owner.generateItem(i,i);
}
clock_t start = clock();
for(int i=0; i<1000; i++)
BOOST_FOREACH(myItem & item, owner.constList)
avoidOptimization+=item.a;
printf ( "%f\n", ( (double)clock() - start ) / CLOCKS_PER_SEC );
start = clock();
for(int i=0; i<1000; i++)
BOOST_FOREACH(myHookedItem & item, owner.nonConstList)
avoidOptimization+=item.a;
printf ( "%f\n", ( (double)clock() - start ) / CLOCKS_PER_SEC );
printf ("%d",avoidOptimization);
return 0;
}
------------ Console Output -----------------
4.690000
4.700000
1764472320

Resources