initialize user-defined objects using lamda expression
Jul 14, 2015 at 9:01am UTC
Hello forum,
I have declared smart pointer as follows:
1 2
std::vector<std::shared_ptr<Line>> lines_;
std::vector<std::shared_ptr<Line>> edgeLines_;
Now I want to call make_shared<Line> over each element of the vector I have declared above. Would lamda expression be a better option than function objects ?
I am not sure how to formulate the syntax.
Thanks
Jul 14, 2015 at 12:44pm UTC
I tried the following : Please let me know how to validate it and is there any better way to accomplish this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <memory>
using namespace std;
class A
{
public :
A():val(nullptr ) {}
~A() { std::cout << "Destructor called" << std::endl;}
private :
int *val;
};
int main()
{
std::vector<std::shared_ptr<A>> allAs;
allAs.resize(120);
for_each(allAs.begin(),allAs.end(),[](std::shared_ptr<A>) -> std::shared_ptr<A> {return std::make_shared<A>();});
return 0;
}
Jul 14, 2015 at 1:31pm UTC
The code looks like it should work, but why are you not using a regular for loop (or a range-based for loop)? I fail to see what advantage std::for_each has in this situation.
Jul 14, 2015 at 2:52pm UTC
I think I am doing something wrong. I tried to check if the memory is actually created with the following snippet and it prints that no memory is allocated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <memory>
using namespace std;
class A
{
public :
A():val(nullptr ) { /*std::cout << "Constructor called" << std::endl; */ }
~A() { /*std::cout << "Destructor called" << std::endl; */ }
private :
int *val;
};
int main()
{
std::vector<std::shared_ptr<A>> allAs;
allAs.resize(120);
std::for_each(allAs.begin(),allAs.end(),[](std::shared_ptr<A> as) mutable {as = std::make_shared<A>();});
//check that memory is actually created
int notInitialized = std::count_if(allAs.cbegin(),allAs.cend(),
[](std::shared_ptr<A> as)
{ return as.get() == 0;});
std::cout << "Number of un-initialized memory: " << notInitialized << std::endl;
return 0;
}
Is the parameter is passed by value ? In this case even copy be value should show the expected result.
Any idea ?
Jul 14, 2015 at 3:02pm UTC
Pass by reference: we want to modify the object in the vector.
1 2 3
// std::for_each(allAs.begin(),allAs.end(),[](std::shared_ptr<A> as) mutable {as = std::make_shared<A>();});
std::for_each( allAs.begin(), allAs.end(),
[]( std::shared_ptr<A>& ptr ) { ptr = std::make_shared<A>(); } );
Or, simpler:
for ( auto & ptr : allAs ) ptr = std::make_shared<A>();
Topic archived. No new replies allowed.