This question already has answers here:
Using member variable in lambda capture list inside a member function
(4 answers)
Closed 5 years ago.
I was writing a lambda function inside a protected void function of this class
class Tetris: protected TetrisArea<true>
{
public:
Tetris(unsigned rx) : TetrisArea(rx), seq(),hiscore(0),hudtimer(0) {}
virtual ~Tetris() { }
protected:
// These variables should be local to GameLoop(),
// but because of coroutines, they must be stored
// in a persistent wrapper instead. Such persistent
// wrapper is provided by the game object itself.
Piece seq[4];
The lambda function,
auto fx = [&seq]() { seq[0].x=4; seq[0].y=-1;
seq[1].x=Width; seq[1].y=Height-4;
seq[2].x=Width+4; seq[2].y=Height-4; };
So here's the problem. I got these errors:
error: capture of non-variable 'Tetris::seq'
auto fx = [&seq]() { seq[0].x=4; seq[0].y=-1;
error: 'this' was not captured for this lambda function
auto fx = [&seq]() { seq[0].x=4; seq[0].y=-1;
.. and also for subsequent reference of seq[n] in the function.
I tried to type the code directly in the protected void function but although it compiles, it doesn't seem to work normally as the program is from the Youtube channel Bisqwit in his Tetris Dos game.
As it reads, you try to capture an object's member without capturing the object itself. Change [&seq] into [this] and see what happens.
Related
This question already has answers here:
What is the lifetime of a static variable in a C++ function?
(5 answers)
Closed 6 years ago.
recently I saw a piece of code as follows :
namespace {
mutex* get_server_factory_lock() {
static mutex server_factory_lock;
return &server_factory_lock;
}
typedef std::unordered_map<string, ServerFactory*> ServerFactories;
ServerFactories* server_factories() {
static ServerFactories* factories = new ServerFactories;
// is variable factories assigned every time this function called ?
return factories;
}
} // namespace
/* static */
void ServerFactory::Register(const string& server_type,
ServerFactory* factory) {
mutex_lock l(*get_server_factory_lock());
if (!server_factories()->insert({server_type, factory}).second) {
LOG(ERROR) << "Two server factories are being registered under "
<< server_type;
}
}
It seems that function server_factories() is similar to the singleton.
My question is : to the best of my knowledge, factories is a static variable, and every time function server_factories() called, this static variable will be assigned a new value. But the result is not, every time server_factories() is called, it returns the same pointer. Why?
PS : with c++11 enabled when compiling.
Duplicated with What is the lifetime of a static variable in a C++ function?
It's a static, so it only gets initialized once, when you first enter the function. Later calls to the same function use the previous variable. That said, I fail to see why it's a pointer and not a simple function static variable (with automatic storage duration) that we could take the address of...
This question already has answers here:
What is this weird colon-member (" : ") syntax in the constructor?
(14 answers)
Closed 7 years ago.
I have a couple of syntax questions that I'm sure most people could answer but this is all foreign to me and I worked through a class tutorial but it left a few questions unanswered.
This code is the declaration line of a class function and inside the parenthesis are the values to be passed. correct?
void HwCounter_IVBNHSX_IMC::SetRegisterLocations(int bus, int ha, int chan, int counterNumber)
{
_ha = ha;
_chan = chan;
_counterNumber = counterNumber;
_bus = bus;
}
In this example what does the additional semicolon at the end enable? Where would I be looking to see what the counterNumbers are associated with?
HwCounter_IVBNHSX_IMC::HwCounter_IVBNHSX_IMC(int hwType, const char* pName) : HwCounterBase(pName)
{
_counterNumber = 0;
_currentConfig = 0;
_hwType = hwType;
}
I'm unable to post the entire source code sorry and I know that makes it more difficult but any help would be appreciated.
This code is the declaration line of a class function and inside the
parenthesis are the values to be passed. correct?
Yes, it is, being understood that the function has to be first declared inside the class.
In this example what does the additional semicolon at the end enable?
HwCounter_IVBNHSX_IMC::HwCounter_IVBNHSX_IMC(..) is a constructor for the class HwCounter_IVBNHSX_IMC.
The : is followed by a list of mem-initializer, a special form of initialization of data members and of the base class if necessary. For example HwCounterBase(pName) means that the data member (or the base class) HwCounterBase is intialized by calling its constructor with the value pName.
This:
void HwCounter_IVBNHSX_IMC::SetRegisterLocations(int bus, int ha, int chan, int counterNumber)
{
...
}
is the definition of a function. (The declaration is something else, and to learn the distinction you should start with a simpler example.) Its name is SetRegisterLocations, it is a member of the class HwCounter_IVBNHSX_IMC, it takes four arguments (all int), and it returns nothing (void).
This:
HwCounter_IVBNHSX_IMC::HwCounter_IVBNHSX_IMC(int hwType, const char* pName)
{
...
}
is similar, but it is a constructor. The name of the function is the same as the name of the function, and it has no return type (not even void).
This:
HwCounter_IVBNHSX_IMC::HwCounter_IVBNHSX_IMC(int hwType, const char* pName) : HwCounterBase(pName)
{
...
}
is the same, but it has an initializer list (consisting of only one initializer) which sets the value (or calls the constructor) of a member variable (HwCounterBase).
Where would I be looking to see what the counterNumbers are associated
with?
The rest of the code.
This question already has answers here:
When should I make explicit use of the `this` pointer?
(12 answers)
Closed 8 years ago.
Background:
I am reading code written by someone else, and I am fairly new to C++ programming. When I look at the classes written by that person, and the corresponding member functions, I get confused with the usage of the this pointer. In some member functions this is used and in others not.
Why is that the case?
I know it is a very common confusion for the ones who start doing C++ recently.
Code Snippets:
The class:
class InitTable {
public:
InitTable();
virtual ~InitTable();
void clearTable();
void addEntry(std::string sumoID);
void deleteEntry(std::string sumoID);
InitEntry* getEntry(std::string sumoID);
IPv4Address getEntryIPaddress(std::string sumoID);
protected:
std::map<std::string, InitEntry*> table;
};
Member function (with this):
void InitTable::clearTable()
{
this->table.clear();
}
Member function (without this):
void InitTable::deleteEntry(std::string sumoID)
{
InitEntry* ie = getEntry(sumoID);
if (ie != NULL)
{
table.erase(sumoID);
delete ie;
}
}
Question:
Note that in void InitTable::clearTable() , this->table.clear() is used and in void InitTable::deleteEntry(), table.erase() only table without this is used.
void InitTable::clearTable()
{
table.clear(); // no "this"
}
What is the trick in here? What would be the behaviour if this->table.erase() would be used instead.
void InitTable::deleteEntry(std::string sumoID)
{
InitEntry* ie = getEntry(sumoID);
if (ie != NULL)
{
this->table.erase(sumoID); // "this" added
delete ie;
}
}
As I said, I'm a bit of n00b so a thorough description with minimal example would be very helpful.
It is never required inside a normal function, unless there is a parameter with the same name as a member. In a constructor you can use an initalizer list to prevent ambiguity. The use of a this pointer might be required when you use templates.
I'm a newbie to arduino and programming.
I've included a library inside my own library in arduino, but first library contains a function which has a pointer function as a parameter. It is an interrupt service routine(ISR) but I need to call a function in my cpp file when interrupt is occurred. So I need to pass the pointer of that function to the first library code. It works well when I use it in .ino file, I can pass it like,
attachInterrupt(functionISR_name);
but when I use it in .cpp file, I get errors. my function is like,
void velocity::functionISR_name(){
//some code
}
but how can I pass the pointer of this function to the first library function? I tried this way but got errors,
attachInterrupt(velocity::functionISR_name);
You cannot pass a method to a function which expects a function, unless you define it static.
write it static :
static void velocity::functionISR_name()
and
attachInterrupt(&velocity::functionISR_name);
Unfortunately the static method is not bound to a specific instance any more. You should use it only together with a singleton. On Arduino you should write the class like shown below in the code snipped:
class velocity
{
static velocity *pThisSingelton;
public:
velocity()
{
pThisSingelton=this;
}
static void functionISR_name()
{
pThisSingelton->CallWhatEverMethodYouNeeded();
// Do whatever needed.
}
// … Your methods
};
velocity *velocity::pThisSingelton;
velocity YourOneAndOnlyInstanceOfThisClass;
void setup()
{
attachInterrupt(&velocity::functionISR_name);
// …other stuff…
}
This looks ugly, but in my opinion it is totally okay with Arduino as the opportunities are very limited on such a system.
Thinking again over it, I would personal go for the approach Sorin mentioned in his answer above. That would be more like that:
class velocity
{
public:
velocity()
{
}
static void functionISR_name()
{
// Do whatever needed.
}
// … Your methods
};
velocity YourOneAndOnlyInstanceOfThisClass;
void functionISR_name_delegation()
{
YourOneAndOnlyInstanceOfThisClass.functionISR_name();
}
void setup()
{
attachInterrupt(functionISR_name_delegation);
// …other stuff…
}
It would also save you some bytes for the pointer you need in the first example.
As a site note: For the future, please post the exact code (for e.g. attachInterrupt needs more parameter) and copy&paste the error messages. Usually error are exact at a place you do not suspect. This question was an exception. Normally I and other would ask for better specification.
You pass a pointer to the function but the function is a class member. Likely the call will be invalid because the this pointer will be garbage(may compile fine but will throw strange errors at runtime).
You need to define a plain vanilla function, outside of any class, and use that.
If you don't have a very complex project you can get away with having a global pointer to the class instance you should use and just delegate the call in your new function.
If you want to do thing the right way you need some mechanism to get the instance pointer I talked about above. Usually this involves either a singleton or some factory pattern.
Example:
class Foo {
void method() {
x = 5;
}
int x;
}
Having a callback on method will crash because you have an invalid pointer for this so x=5 will write 5 somewhere randomly in memory.
What you need is somehting like:
static Foo* foo_instance; // Initialized somewhere else.
void method_delegator() {
foo_instance->method();
}
Now you can pass method_delegator to the function. It will work because you now also pass foo_instance for this pointer.
This question already has answers here:
Start thread with member function
(5 answers)
Closed 9 years ago.
I am trying to call some of my member functions using threads. Suppose I have this
class myclass
{
public:
myclass();
double function1();
void function2();
};
myclass::myclass()
{}
double myclass::function1()
{
...
return a double;
}
void myclass::function2()
{
//use a thread to call function 1
std::thread t(function1);//doesnt work!-wont compile
std::thread t2(myclass::function1);//doesnt work either -wont compile
std::thread t3(&myclass::function1);//doesnt work here either - wont compile
}
How can I call a member function by a thread inside another member function in C++?
I am using Visual Studio 2013 Preview by the way.
UPDATE 2:
I did as i was told , some sections of code now compiles just fine and some others just don't!
this is the new sample code which generates the error :
class xGramManipulator
{
public:
xGramManipulator();
void ReadMonoGram();
void ReadBiGram();
void ReadMonoGram(double &);
void ReadBiGram(double &);
void CreateMonoGramAsync();
void CreateBiGramAsync();
};
xGramManipulator::xGramManipulator()
{
}
void xGramManipulator::CreateMonoGramAsync()
{
thread t(&xGramManipulator::ReadMonoGram, this);
}
void xGramManipulator::CreateBiGramAsync()
{
thread t = thread(&xGramManipulator::ReadBiGram, this);
}
The above code(those two Async member functions) generates the following errors :
Error Message:
error C2661: 'std::thread::thread' : no overloaded function takes 2 arguments
Say std::thread(&myclass::function1, this).
If you need to disambiguate overloads, you have to cast the function pointer explicitly:
std::thread(static_cast<void (xGramManipulator::*)()>(&xGramManipulator::ReadMonoGram), this)
Try using boost::bind as described here to bind the implicit "this" parameter of a member function:
How to use boost bind with a member function
This will make it a function without parameters and you can use it to start a thread.