My code goes like this :
struct foo {
int first;
int second;
};
void func(foo& A) {
Schedule([=]()
{
DoWork(A.first, A.second)
});
}
Does lambda capture the reference to the struct by value or does it capture the .first and and .second by value ?
Thanks,
Take the following code:
#include <iostream>
using namespace std;
class NeedDeepCopy
{
public:
NeedDeepCopy()
{
};
NeedDeepCopy(const NeedDeepCopy& other)
{
data = new int[1];
data[0] = 0x90;
}
int *data;
};
void func(NeedDeepCopy& obj) {
auto lambda = [=]() mutable
{
if(*obj.data == 0x90)
cout << "0x90 - a copy was made";
};
if(*obj.data == 0x88)
cout << "Original value is 0x88" << endl;
lambda();
}
int main() {
NeedDeepCopy obj;
obj.data = new int[1];
*obj.data = 0x88;
func(obj);
// your code goes here
return 0;
}
http://ideone.com/Ws6KJX
The answer is: a copy to the entire object / structure is made. In case you're dealing with objects which need a deep copy, you need to pay attention otherwise you might get uninitialized data.
By value, if you want to capture by ref it is [&]
If you want to capture a by value and b by ref you put [a,&b]
Related
void ZMDAggregator::getMZMap(DataModel::MZMap &mZM)
{
LOGGER_EVENT("ZMDAggregator getMZMap()");
std::unique_lock<std::mutex> lockSlot(internalStateMutex);
mZM.clear();
mZM = this->mZM;
}
void ZMDAggregator::Roscallback(const ros::MZMap msgMZMap)
{
std::unique_lock<std::mutex> lockSlot(internalStateMutex);
MZMap map;
for( auto const & entry : msgMZMap.m_z_e)
{
mzEntry.clear();
mzEntry.mID = entry.mID;
mzEntry.tMode = entry.tMode;
mzEntry.areaID = entry.areaID;
mzEntry.oZone = entry.oZone;
mzEntry.authZ = entry.authZ;
mzEntry.blockZ = entry.blockZ;
map.mzEntry.push_back(mzEntry);
}
}
The above function gets called around 30 times a second.This is causing a high cpu utilization in my program.
struct MZEntry
{
uint32_t mID;
bool tMode;
uint32_t areaID;
uint32_t oZone;
using ZList = std::vector<uint32_t>;
ZList authZ;
ZList blockZ;
};
struct MZMap
{
std::vector<MZEntry> mzEntry;
}
Class ZMDAggregator {
mutable std::mutex internalStateMutex;
MZMap mzMap;
}
My question is if I convert getMZMap() to accept a shared_ptr instead of a reference and also change the type of the member variable mzMap to a shared_ptr as shown below.
void ZMDAggregator::getMZMap(std::shared_ptr<DataModel::MZMap> &mZM)
{
LOGGER_EVENT("ZMDAggregator getMZMap()");
std::unique_lock<std::mutex> lockSlot(internalStateMutex);
mZM = this->mZM;
}
Class ZMDAggregator {
mutable std::mutex internalStateMutex;
std::shared_ptr<DataModel::MZMap> mzMap;
}
My question is as follows.
My class ZMDAggregator updates the structure once every 50 milliseconds, so around 20 times a second As you can see this happens inside the unique_lock.
The Thread that calls, getMZMap() calls it around 20 times a second.
By modifying initial structure to a shared_ptr, I should be able to bring down CPU cycles, as a struct copy is now avoided. However now since the same pointer is being accessed in the caller thread (Reader)
there is a risk that I can get half an old pointer and half a new pointer when the function Roscallback updates the structure.
Without using a mutex, (These two functions are two separate classes) is there a way to ensure that the above scenario doesn't occour ?
As per the suggestion of #freakish, I have returned shared_ptr by value. Please find the code below.
#include <iostream>
#include <memory>
#include <vector>
struct MZEntry
{
uint32_t mID;
bool tMode;
uint32_t areaID;
uint32_t oZone;
using ZList = std::vector<uint32_t>;
ZList authZ;
ZList blockZ;
};
struct MZMap
{
std::vector<MZEntry> mzEntry;
};
class A
{
public:
void populate()
{
std::cout << "A populate()" << std::endl;
MZEntry mzEntry;
mzEntry.mID = 55;
mzEntry.tMode = true;
mzEntry.areaID = 55;
mzEntry.oZone = 55;
mzEntry.authZ = {1,2,3};
mzEntry.blockZ = {4,5,6};
l->mzEntry.push_back(mzEntry);
}
std::shared_ptr<MZMap> assign() const
{
return l;
}
std::shared_ptr<MZMap> l;
A()
{
std::cout << "A constructor()" << std::endl;
l = std::make_shared<MZMap>();
populate();
}
};
class B
{
public:
B()
{
std::cout << "B constructor" << std::endl;
a = new A();
}
void getValue()
{
std::cout << "B getValue()" << std::endl;
p3 = a->assign();
}
void print()
{
std::cout << "machineID: " << p3->mzEntry[0].mID << std::endl;
}
std::shared_ptr<MZMap> p3;
A *a;
};
int main() {
B *b = new B();
b->getValue();
b->print();
return 0;
}
So what you are saying is in the line
p3 = a->assign();
It doesn't do a struct copy, instead it just increments the reference count? Is my understanding correct?
I simplified the code, so pardon my style.
I was wondering what happens to an object that is constructed by a constructor that actually allocates memory, and passed to a lambda by value, when this lambda itself, is being a callback by another thread.
It didn't surprise me to see the program crashes when the destructor is called. This was test#1.
test#2: I removed the "new" and the "delete[]" from c'tor and d'tor of A, and now - it worked fine.
test#3:
I brought the "new" and the "delete[]" back as before, but now I changed every place with "A objA" (by value) into "A& objA", and now, it didn't crash as well.
Now, I can rationalize it by waving my hands but I'd like to understand what really happened here, and for that matter - what would happen if an object that is passed into a lambda by "capture", also ceases to exist.
and last question: is there a good practice or tip what to do (or what to avoid) in such cases?
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
using namespace std::chrono_literals;
class A {
public:
A() : x(1) { ptr = new char[1024]; }
~A() { delete[](ptr); }
int getX() { return x; }
private:
int x = 0;
char* ptr = nullptr;
};
std::function<void(A objA)> myCb;
int myThread()
{
static int counter = 0;
auto a = new A;
while (true) {
std::this_thread::sleep_for(2s);
if (myCb)
myCb(*a);
else
std::cout << "myCb is still NULL: counter = " << counter << std::endl;
if (counter++ == 5)
break;
}
return 0;
}
void registerCallback(std::function<void(A obj)> cb)
{
myCb = cb;
}
int main()
{
std::thread t1(myThread);
std::this_thread::sleep_for(6s);
int val = 5;
registerCallback([&val](A objA) {
std::cout << "here lambda is called with " << objA.getX() << " and " << val << std::endl;
});
val = 6;
std::this_thread::sleep_for(1s);
val = 7;
std::this_thread::sleep_for(1s);
val = 8;
std::this_thread::sleep_for(1s);
t1.join();
}
class A is violating the Rule of 3/5/0, as it does not implement a copy-constructor and/or move-constructor, or a copy-assignment and/or move-assignment operator.
So, when an instance of A is passed around by value, a shallow copy is made that shares the same char* pointer to a single char[] array in memory, and thus the code MAY crash (ie, undefined behavior) when trying to delete[] that same array multiple times.
What you need is a deep copy instead, so that each instance of A allocates its own char[] array, eg:
class A
{
public:
A() : x(1), ptr(new char[1024])
{
std::fill(ptr, ptr + 1024, '\0');
}
A(const A &src) : x(src.x), ptr(new char[1024])
{
std::copy(src.ptr, src.ptr + 1024, ptr);
}
A(A &&src)
: x(src.x), ptr(src.ptr)
{
src.ptr = nullptr;
}
~A()
{
delete[] ptr;
}
A& operator=(A rhs)
{
std::swap(x, rhs.x);
std::swap(ptr, rhs.ptr);
return *this;
}
int getX() const { return x; }
private:
int x;
char* ptr;
};
A simpler way to implement this is to use std::vector instead of new[], since vector is already compliant with the Rule of 3/5/0, and so compiler-generated constructors, destructor, and assignment operators for A will suffice to make copies/moves of the vector for you, eg:
#include <vector>
class A
{
public:
A() : vec(1024, '\0') {}
int getX() const { return x; }
private:
int x = 1;
std::vector<char> vec;
};
You should use unique_ptr. deleting a void* is undefined behavior
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
using namespace std::chrono_literals;
class A {
public:
A() : x(1)
{
ptr = std::make_unique<char[]>(1024);
}
~A()
{
}
int getX() { return x; }
private:
int x = 0;
std::unique_ptr<char[]> ptr = nullptr;
};
std::function<void(A& objA)> myCb;
int myThread()
{
static int counter = 0;
auto a = new A;
while (true) {
std::this_thread::sleep_for(2s);
if (myCb)
myCb(*a);
else
std::cout << "myCb is still NULL: counter = " << counter << std::endl;
if (counter++ == 5)
break;
}
return 0;
}
void registerCallback(std::function<void(A& obj)> cb)
{
myCb = cb;
}
int mymain()
{
std::thread t1(myThread);
std::this_thread::sleep_for(6s);
int val = 5;
registerCallback([&val](A& objA) {
std::cout << "here lambda is called with " << objA.getX() << " and " << val << std::endl;
});
val = 6;
std::this_thread::sleep_for(1s);
val = 7;
std::this_thread::sleep_for(1s);
val = 8;
std::this_thread::sleep_for(1s);
t1.join();
return 0;
}
I am currently working on a chess engine in C++, and in the engine, I'm trying to modify a string variable "piece" inside of a class "ChessTile" within another class called "ChessBoard".
Anyways when I use a function to return a class, then modify said class, it doesn't change the source variable, and I was wondering how you do that.
Here is a simple script I wrote to demonstrate:
#include <iostream>
#include <string>
class child {
private:
int myVar;
public:
child(int v) {
myVar = v;
}
int getVar() {
return myVar;
}
int setVar(int Svar) {
this->myVar = Svar;
return 0;
}
};
class parent {
public:
child baby = child(0);
child findMyChild(int var) {
if (var == 1) {
return baby;
}
}
};
parent DAD;
int main() {
std::cout << DAD.findMyChild(1).getVar() << std::endl;
DAD.findMyChild(1).setVar(50);
std::cout << DAD.findMyChild(1).getVar() << std::endl;
}
The output for this is:
0
0
But I'm wanting it to be:
0
50
If necessary, I can also post my chess engine. Thank you!
In your code, findMyChild() is returning a copy of the baby ( function returning by value), use return by reference instead like so.
child& parent::findMyChild(int var) {
if (var == 1)
{
return baby;
}
/* other codes */
return baby;
}
You are returning a copy of child in findMyChild. Therefore, you modify only that copy, not the member itself.
You should return a pointer to the member
child* findMyChild(int var) {
return var == 1
? &baby
: nullptr;
}
then dereference it to get/set its value. For example:
DAD.findMyChild(1)->setVar(50);
Since findMyChild can return null pointer in my code you should check its existence before accessing
child* c = DAD.findMyChild(1);
if (c) c->setVar(50);
You can do it via returning pointer/reference of child as stated by another comment or you can do it via an interface in parent class.
#include <iostream>
#include <string>
#define FIRST_CHILD 1
#define CANNOT_FIND_CHILD -1
class child {
private:
int myVar;
public:
child(int v) {
myVar = v;
}
int childGetVar() {
return myVar;
}
int childSetVar(int Svar) {
this->myVar = Svar;
return 0;
}
};
class parent {
public:
child baby = child(0);
int getVar(int var) {
if (var == FIRST_CHILD)
return baby.childGetVar();
return CANNOT_FIND_CHILD;
}
int setVar(int var, int Svar) {
if (var == FIRST_CHILD)
baby.childSetVar(Svar);
return CANNOT_FIND_CHILD;
}
};
parent DAD;
int main() {
std::cout << DAD.getVar(FIRST_CHILD) << std::endl;
DAD.setVar(FIRST_CHILD, 50);
std::cout << DAD.getVar(FIRST_CHILD) << std::endl;
}
Is it possible to use a lambda function to create an alias to a template class function? Something like this:
#include <iostream>
using namespace std;
int calcDouble(int a) { return a * 2; }
int calcMultiply_10(int a) { return a * 10; }
struct foo
{
template<void (*func)(int)>
int generic(int value)
{
return func(value);
}
static auto double_10 = [this] { generic<calcDouble>(10); };
static auto double_20 = [this] { generic<calcDouble>(20); };
static auto multiply_10_20 = [this] { generic<calcMultiply_10>(20); };
}
int main() {
foo f;
cout << "double_10: " <<f.double_10() << endl;
cout << "double_20: " <<f.double_20() << endl;
return 0;
}
Your particular example doesn't compile, and would be dangerous if it did - capturing this by value means that as soon as the class is copied/moved the captured this will point to a wrong or invalid memory location.
Just use member functions:
auto double_10() { return generic<calcDouble>(10); }
auto double_20() { return generic<calcDouble>(20); }
auto multiply_10_20() { return generic<calcMultiply_10>(20); }
live example on wandbox
my type aButton has a function pointer so i can define custom actions for each button, i though the easiest way to do this would be to create a lambda and dereference it and pass it to the function pointer of that aButton instance, since i need non-static access to objects outside of the scope of the button class
but i'm stuck trying to figure out how to cast it to the right type and how to call it without getting the errors below... i haven't see many people have luck with this, and using functional doesn't look like i can pass in context???
// Example program
#include <iostream>
#include <string>
int global1 = 0;
int global2 = 5;
class aButton {
public:
int status, oldStatus;
aButton(int initStatus) { oldStatus = status = initStatus; }
int (aButton::*action)();
};
class Thingy {
private:
int mode = 1;
int value = 0;
public:
void reset() { value = 0; }
void setMode(int newMode) { mode = newMode; }
void increment() { value = value + global2; }
//accessors & mutators
};
void specialFunction(Thingy *thingyToWorkOn) {
//do stuff...
}
void anotherSpecialFunction(Thingy *firstThingy, Thingy *secondThingy) {
//more stuff...
}
int main() {
Thingy one;
Thingy two;
aButton *on = new aButton(0);
aButton *speedUp = new aButton(0);
on->action = &( //error: taking address of temporary [-fpermissive]
[&]() { //error: cannot convert 'main()::<lambda()>*' to 'int (aButton::*)()' in assignment
//some specific stuff....
global1 = 1;
if (global2 < 10) {
global2++;
}
one.reset();
two.reset();
anotherSpecialFunction(&one, &two);
std::cout << "on action \n";
return 1;
}
);
speedUp->action = &( //error: taking address of temporary [-fpermissive]
[&]() { //error: cannot convert 'main()::<lambda()>*' to 'int (aButton::*)()' in assignment
//some specific stuff....
if (global1) {
one.setMode(global2);
two.setMode(global2);
specialFunction(&one);
specialFunction(&two);
std::cout << "speedUp action \n";
return 1;
}
return 0;
}
);
for(int i=0; i<5; i++) {
//if on pushed
(on->(on->action))(); //error: expected unqualified-id before '(
//if speedUp pushed
(speedUp->(speedUp->action))(); //error: expected unqualified-id before '(
}
}
I believe that you want aButton::action to be of type std::function<int()> (read: function that takes nothing and returns int) rather than int (aButton::*). This requires the <functional> header. With that change, your assignments could stay the same (minus the leading address-of operator), though as you figured out, you'll need to explicitly state the return type with -> int. The calls would simply take the form (e.g.):
on->action();
One other note: be very careful about capturing local variables (one, two) by reference. If the function really is main then I suppose it's ok since main won't return until the program ends, but otherwise it would be asking for trouble.
You cannot assign pointer to lambda to pointer to member function. Pointers to member functions may point only to member functions.
You can indeed use std::function from <functional> instead. Declare your action as
std::function<int()> action;
so instead of using member functions you will use global functions. Of course you need to get rid of & operators for lambdas. And you need to modify the way of calling action.
Thanks guys, i guess functional was what i was looking for after all... this seems to do what i want on http://cpp.sh/8ll i guess i just got confused cause a lot of the functional examples had them as arguments for callbacks instead
// Example program
#include <iostream>
#include <string>
#include <functional>
int global1 = 0;
int global2 = 5;
class aButton {
public:
int status, oldStatus;
aButton(int initStatus) { oldStatus = status = initStatus; }
std::function<int()> action;
};
class Thingy {
private:
int mode = 1;
int value = 0;
public:
void reset() { value = 0; }
void setMode(int newMode) { mode = newMode; }
void increment() { value = value + global2; }
//...
};
void specialFunction(Thingy *thingyToWorkOn) {
//do stuff...
}
void anotherSpecialFunction(Thingy *firstThingy, Thingy *secondThingy) {
//more stuff...
}
int main() {
Thingy one;
Thingy two;
aButton *on = new aButton(0);
aButton *speedUp = new aButton(0);
on->action = std::function<int()>(
[&]() -> int{
//some specific stuff....
global1 = 1;
if (global2 < 10) {
global2++;
}
one.reset();
two.reset();
anotherSpecialFunction(&one, &two);
std::cout << "on action \n";
return 1;
}
);
speedUp->action = std::function<int()>(
[&]() -> int{
//some specific stuff....
if (global1) {
one.setMode(global2);
two.setMode(global2);
specialFunction(&one);
specialFunction(&two);
std::cout << "speedUp action \n";
return 1;
}
return 0;
}
);
for(int i=0; i<5; i++) {
//if on pushed
on->action();
//if speedUp pushed
speedUp->action();
}
}