PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label this. Show all posts
Showing posts with label this. Show all posts

Saturday, November 5, 2022

[FIXED] How to get value from a vector by value from another vector?

 November 05, 2022     c++, c++11, lambda, this     No comments   

Issue

I have two vectors:

one contains numbers and names of things;

second collects numbers that have already been showed to the user;

I'm trying to make a history list of all objects that have been shown.

Here is my code:

class palettArchive{
private:
    std::vector<std::pair<int,std::string>> paletts;
    int palletsCounter;
    std::vector<int> choosen;
public:
    //...
    void history(){
        auto  printHist = [](int& i){
            int tmp = i;
            std::pair<int,std::string> tempPair = paletts[tmp];
            std::cout << tempPair.first << " " << tempPair.second;
            return 0;
        };
        std::for_each(choosen.begin(), choosen.end(), printHist);
    }
};

There is an error:

error: 'this' cannot be implicitly captured in this context
         std::pair<int,std::string> tempPair = paletts[tmp];

I can't make a third vector with the list that is created already. I need to make it by calling a function and printing at the time.


Solution

for_each and lambda are just making your life difficult. The simpler code is explicit iteration:

void history()
{
    for (auto i : choosen) {
        auto tempPair = paletts[i];
        std::cout << tempPair.first << " " << tempPair.second;
                                    // did you mean to send a newline "\n" also?
    }
}


Answered By - Ben Voigt
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, November 4, 2022

[FIXED] Why do lambda functions need to capture [this] pointer explicitly in c++20?

 November 04, 2022     c++, c++20, capture, lambda, this     No comments   

Issue

Pre-c++20, the this pointer is captured in [=] implicity. So what's the reason that c++20 decided that user should write [=, this] to capture this pointer explicitly, I mean, without this change, the pre-c++20 code could have any code-smell or potential bug?

Any good sample or reason for this language change?


Solution

This is explain in P0806, which as the title says, "Deprecate[d] implicit capture of this via [=]"

The argument in the paper is that at this point we had [this] (captures the this pointer) and [*this] (captures the object itself), and [&] (captures the object by reference, which is basically capturing the this pointer by value). So it could be ambiguous whether [=] should mean [this] or [*this] and potentially surprising that it means the former (since [=] functions as a reference capture in this context).

Thus, you have to write [=, this] or [=, *this], depending on which one of the two you actually intended.


As an aside, it's worth nothing that the paper claims:

The change does not break otherwise valid C++20 code

Yet if you compile with warnings enabled and -Werror, as many people do (and should unless you have a compelling reason not to - which there are), this change of course broke lots of otherwise valid C++20 code.



Answered By - Barry
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, November 3, 2022

[FIXED] How to define a lambda function to be able to capture the 'this' pointer of a class?

 November 03, 2022     arduino-esp32, c++, capture, lambda, this     No comments   

Issue

I have a time class which tracks the time.

I want my other classes to be able to register a callback function if the day changes.

I have this working snippet:

#define MAX_CB_CHANGE_FUNCTIONS 50
typedef void (*dayChangeFunc)(int prevDay,int nowDay);

class TimeSystem {
    private:
        // array for the function pointers.
        dayChangeFunc dayChangeFunctions[MAX_CB_CHANGE_FUNCTIONS];
        // emit function if the day changes.
        void emitDayChange(int prev, int now);
    public:
        void regDayChange(dayChangeFunc);
};


/*
*   Registering a day change function.
*   Maximum function pointer count is MAX_CB_CHANGE_FUNCTIONS ( see timeSys.h )
*/
void TimeSystem::regDayChange(void (*dayChangeFunc)(int prevDay,int nowDay)){
    if( currDayCbIndex >= MAX_CB_CHANGE_FUNCTIONS ){
        if(isDebugOn){
            debug.print(DEBUG_WARN,"[Time_sys] - Can not register an other day change function.\n");
            return;
        }
    }
    dayChangeFunctions[currDayCbIndex] = dayChangeFunc;
    currDayCbIndex++;
}

/*
*   Emitting day change to every registered function.
*/
void TimeSystem::emitDayChange(int prev, int now){
    // Preventing change on initialization.
    if( prev == 0 ){ return; }
    for (size_t i = 0; i < MAX_CB_CHANGE_FUNCTIONS; i++){
        if(dayChangeFunctions[i]){
            dayChangeFunctions[i](prev,now);
        }
    }
}

This works and other calsses can use this like this:

timeSys.regDayChange([](int prevDay,int nowDay){
    Serial.printf("Day changed from prev: %d to now: %d\n",prevDay,nowDay);
});

Now i want to capture the 'this' pointer in the lambda to be able to call some internal function of a class.

timeSys.regDayChange([this](int prevDay,int nowDay){
    callSomeInternalFunction();
});

Error i get:

no suitable conversion function from "lambda [](int prevDay, int nowDay)->void" to "dayChangeFunc"

How could i define my lambda to be able to capture the 'this' pointer?

******** EDIT: SOLVED ********

Here are the modifications:

I had to define my lambda function type like this:

using dayChangeFunc = std::function<void(int, int)>;

Define the function pointer register function like this:

void regDayChange(dayChangeFunc cb);

And rewrite the declaration like this:

/*
*   Registering a day change function.
*   Maximum function pointer count is MAX_CB_CHANGE_FUNCTIONS ( see timeSys.h )
*/
void TimeSystem::regDayChange( dayChangeFunc cb ){
    if( currDayCbIndex >= MAX_CB_CHANGE_FUNCTIONS ){
        if(isDebugOn){
            debug.print(DEBUG_WARN,"[Time_sys] - Can not register an other day change function.\n");
            return;
        }
    }
    dayChangeFunctions[currDayCbIndex] = cb;
    currDayCbIndex++;
}

And now i can use it in any class like this:

class SampleClass(){
  private:
     int exampleCounter = 0;
  public:
    void init(){
      TimeSystem timeSys;
      timeSys.regDayChange([this](int prevDay,int nowDay){
        Serial.printf("Day changed from prev: %d to now: %d\n",prevDay,nowDay);
        exampleCounter++;
      });
    }
}

Solution

Change the callback type to std::function<void(int, int)>

using dayChangeFunc = std::function<void(int, int)>;

or

typedef std::function<void(int, int)> dayChangeFunc;

and change the function prototype,

void TimeSystem::regDayChange(dayChangeFunc func).

(If you had used your type alias consistently you wouldn't have needed to change the prototype, only the alias itself. Type aliases are most useful if you use them.)



Answered By - molbdnilo
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, October 20, 2022

[FIXED] What can a 'const' method change?

 October 20, 2022     c++, class-method, const-method, datamember, this     No comments   

Issue

C++ methods allow a const qualifier to indicate that the object is not changed by the method. But what does that mean? Eg. if the instance variables are pointers, does it mean that the pointers are not changed, or also that the memory to which they point is not changed?

Concretely, here is a minimal example class

class myclass {
  int * data;

  myclass() {
    data = new int[10];
  }

  ~myclass() {
    delete [] data;
  }

  void set(const int index) const {
    data[index] = 1;
  }
};

Does the method set correctly qualify as const? It does not change the member variable data, but it sure does change the content of the array.


Solution

Most succinctly, it means that the type of this is const T * inside const member functions, where T is your class, while in unqualified functions it is T *.

Your method set does not change data, so it can be qualified as const. In other words, myclass::data is accessed as this->data and is of type int * const.



Answered By - Kerrek SB
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 10, 2022

[FIXED] Why is 'this' a pointer and not a reference?

 July 10, 2022     c++, c++-faq, pointers, reference, this     No comments   

Issue

I was reading the answers to this question C++ pros and cons and got this doubt while reading the comments.

programmers frequently find it confusing that "this" is a pointer but not a reference. another confusion is why "hello" is not of type std::string but evaluates to a char const* (pointer) (after array to pointer conversion) – Johannes Schaub - litb Dec 22 '08 at 1:56

That only shows that it doesn't use the same conventions as other (later) languages. – le dorfier Dec 22 '08 at 3:35

I'd call the "this" thing a pretty trivial issue though. And oops, thanks for catching a few errors in my examples of undefined behavior. :) Although I don't understand what info about size has to do with anything in the first one. A pointer is simply not allowed to point outside allocated memory – jalf Dec 22 '08 at 4:18

Is this a constant poiner? – yesraaj Dec 22 '08 at 6:35

this can be constant if the method is const int getFoo() const; <- in the scope of getFoo, "this" is constant, and is therefore readonly. This prevents bugs and provides some level of guarantee to the caller that the object won't change. – Doug T. Dec 22 '08 at 16:42

you can't reassign "this". i.e you cannot do "this = &other;", because this is an rvalue. but this is of type T*, not of type T const . i.e it's a non-constant pointer. if you are in a const method, then it's a pointer to const. T const . but the pointer itself is nonconst – Johannes Schaub - litb Dec 22 '08 at 17:53

think of "this" like this: #define this (this_ + 0) where the compiler creates "this_" as a pointer to the object and makes "this" a keyword. you can't assign "this" because (this_ + 0) is an rvalue. of course that's not how it is (there is no such macro), but it can help understand it – Johannes Schaub - litb Dec 22 '08 at 17:55

My question is, why is this a pointer a not a reference? Any particular reason for making it a pointer?


Some further arguments why this being a reference would make sense:

  • Consider Item 1 from More Effective C++ : use references when it is guaranteed that we have a valid object i.e. not a NULL (my interpretation).
  • Furthermore, references are considered safer than pointers (because we can't screw the memory up with a stray pointer).
  • Thirdly, the syntax for accessing references (.) is a little bit nicer and shorter than accessing pointers (-> or (*)).

Solution

When the language was first evolving, in early releases with real users, there were no references, only pointers. References were added when operator overloading was added, as it requires references to work consistently.

One of the uses of this is for an object to get a pointer to itself. If it was a reference, we'd have to write &this. On the other hand, when we write an assignment operator we have to return *this, which would look simpler as return this. So if you had a blank slate, you could argue it either way. But C++ evolved gradually in response to feedback from a community of users (like most successful things). The value of backward compatibility totally overwhelms the minor advantages/disadvantages stemming from this being a reference or a pointer.



Answered By - Daniel Earwicker
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why does this code cause "this reference" to escape implicitly?

 July 10, 2022     escaping, java, java.util.concurrent, reference, this     No comments   

Issue

What does "When the inner EventListener instance is published,so is the enclosing ThisEscape instance." mean?

This quote is from 《java Concurrency in Practice》

public class ThisEscape {
public ThisEscape(EventSource source)
{
    source.registerListener(
            new EventListener(){
                public void onEvent(Event e)
                {
                    doSomething(e);
                }
            }
    );
}

}


Solution

ThisEscape instance is published during construction because doSomething is a method of ThisEscape , which can cause unforeseen problems.

A simple code example, when a event occurs, the ThisEscape object has not yet been built, but since this ThisEscape is registered with the EventSource, then onSomeThing method is triggered, and an NPE is generated because ThisEscape#data has not yet been initialized:

public class ThisEscape {
    static class EventSource {
        private List<EventListener> eventListeners = new ArrayList<>();
        public void registerListener(EventListener eventListener) {
            eventListeners.add(eventListener);
        }
        public void eventHappen(Event event) {
            eventListeners.forEach(eventListener -> {
                eventListener.onEvent(event);
            });
        }
    }
    static class Event {
        public String eventString;
        public Event(String eventString) {
            this.eventString = eventString;
        }
    }
    interface EventListener {
        void onEvent(Event e);
    }
    private List<String> data;
    public void doSomething(Event e) {
        data.add(e.eventString);
    }
    public ThisEscape(EventSource source) {
        source.registerListener(
                new EventListener() {
                    public void onEvent(Event e) {
                        doSomething(e);
                    }
                }
        );
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.data = new ArrayList<>();
    }
    public static void main(String[] args) {
        EventSource eventSource = new EventSource();
        new Thread(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            eventSource.eventHappen(new Event("hello"));
        }).start();
        ThisEscape thisEscape = new ThisEscape(eventSource);
    }
}


Answered By - zysaaa
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to pass this by ref in C#?

 July 10, 2022     .net, c#, reference, this     No comments   

Issue

In a class (ClassA) of mine I want to create a related instance of another class (ClassB) providing it with a reference to the object who has initiated it's creation. So I've provided ClassB with a construcror taking a (ref ClassB parent) argument. But in ClassA I can't just call var child = new ClassB(ref this). How to implement this?


Solution

The ref keyword causes Pass by Reference semantics - that is, if the variable is re-assigned in the called function, it will re-assign the variable in the caller as well.

Obviously, this only works if a variable2 (which can be re-assigne to) is directly passed as the argument and will not work if an arbitrary expression is passed. In this case, this is not a variable, rather a special expression which cannot be re-assigned, and so cannot be used.

As such, this would work: (But please see other answers and keep reading as to why this is likely not required and/or just silly.)

var me = this;
var other = new ClassB(ref me);

However, Pass by reference should not be confused with Pass by Object [Sharing]1 semantics. Pass by Object means that if an object is passed, that object is passed: the object is not copied/cloned/duplicated. If the object is mutated then the object is mutated. All Reference Types have Pass by Object semantics in C# unless either ref or out are used. (The class keyword declares a new reference type, as in the case in the post).

On the other hand, Value Types (e.g. struct), including int and Guid and KeyValuePair<K,V>, have Pass by Value semantics - in this case a copy is made and thus, if the value is modified, only the value struct (which is a copy) changes.

Happy coding


1 Underneath C#/.NET achieves Pass by Object by passing a reference to an object by Value. However, the rules above correctly describe the observable semantics and effects.

2 Unlike C#, which only allows variables to be used with ref, VB.NET allows Properties to be used. The VB.NET compiler automatically creates a temporary variable and implicit reading/writing instructions of the property during compilation.



Answered By - user166390
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, July 7, 2022

[FIXED] How to reconcile 'this' referencing DOM element and 'this' referencing class?

 July 07, 2022     class, javascript, jquery, this     No comments   

Issue

I'm having an issue understanding how I might go about using the this keyword to refer to a DOM element that is has been clicked, but also using that inside a class where this usually refers to the instance of that class.

Here's a snippet of the relevant code:

class Passwords {
  constructor() {
    $('.password-column button.steel-button').on('click', this.selectButton);
  }
  
  selectButton() {
    $(this).toggleClass('selected');
    this.columnController();
  }
  
  columnController(){
    // A function that does something else
  }
}

The issue I'm having is that it doesn't recognize columnController() as a function. I imagine this is because of the scope and how it works with 'this', but I'm not sure how to proceed.

In the above code, selectButton() is successfully applied to all the buttons specified, but the error is given on this.columnController(). Exact console error is:

Uncaught TypeError: this.columnController is not a function

Thank you in advance.


Solution

You can't use this to represent both objects, so pick one and get the other one through some other mechanism.

For example: Use an arrow function to bind the this value to the class, then get the element from the event object.

class Passwords {
  constructor() {
    $('.password-column button.steel-button').on('click', this.selectButton);
  }

  selectButton = (event) => {
    $(event.currentTarget).toggleClass('selected');
    this.columnController();
  }

  columnController() {
    console.log("this runs");
  }
}

new Passwords();
.selected {
  background: blue
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="password-column">
  <button class="steel-button">click</button>
</div>



Answered By - Quentin
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, June 25, 2022

[FIXED] How to solve a "cannot assign to 'this' as it is readonly" error c#

 June 25, 2022     c#, compiler-errors, datatable, json, this     No comments   

Issue

I am creating a class that creates my own custom table using DataTable.

I want it so that if a json file with the DataTable's info is on my computer; the code will put the json file into that instance of the object (done in the constructor)

This is how i am trying to do it

public Table(string jsonfile)
    {
        if(File.Exists(jsonfile))
        {
            this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
            return;
        }
        formatRegisterTable(jsonfile);
    }

this line is causing the error

this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));

How can I do this without the error?

The full code of the class if needed:

using System.IO;
using System.Data;
using Newtonsoft.Json;

namespace abc.classess._table
{
     class Table
    {
        public DataTable mTable = new DataTable("table");
        private DataColumn mColumn;
        private DataRow mRow;
        

        public Table(string jsonfile)
        {
            if(File.Exists(jsonfile))
            {
                this = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
                return;
            }
            formatRegisterTable(jsonfile);
        }

        private void formatRegisterTable(string jsonfile) 
        {
            //formatting table code

            File.WriteAllText(jsonfile,JsonConvert.SerializeObject(this));
        }
    }
}

Solution

Something like this should solve your problem:

Inside you Table class create the following function:

 public static Table Create(string jsonfile)
 {
       if (File.Exists(jsonfile))
       {
            Table table = JsonConvert.DeserializeObject<Table>(File.ReadAllText(jsonfile));
            return table;
        }
        
        return new Table(jsonfile);
  }

Your table constructor should look now like this:

 public Table(string jsonfile)
 {
    formatRegisterTable(jsonfile);
 }

Then you can use it in ur code var newTable = Table.Create(jsonFile);



Answered By - Somar Zein
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, May 18, 2022

[FIXED] What is difference between this.PropertyName and _PropertyName?

 May 18, 2022     c#, class, linq-to-sql, partial, this     No comments   

Issue

as I often let LinqToSql generate partial entity classes, I am wondering if my practice of adding additional properties via code is correct and if there is a better way of doing the same thing? I am also wondering what is the difference between accessing the values of other properties using this.PROPERTY_NAME vs _PROPERTY_NAME? In my web app I keep using this.PROPERTY_NAME, but I am wondering if that is, as I already said in opening sentence, the proper approach I should be using. Also, What is _PROPERTY_NAME and when do we use it?

Example:

public partial class User
{
    public bool IsThisProper {
        get{
            return this.SomeIntProperty == 10; // I usually use this
        }  
    }

    public bool WhenToUseThisApproach {
        get{
            return _SomeIntProperty == 10; // What is this in comparison to above?
        }  
    }
}

Solution

One is the property, and the other is the private backing field in which that property stores it's value. If you want to execute whatever code the property has in it's getter/setter, then use the property, if you don't, then don't. Chances are you want to use the property, not the field, especially with setting (setting it triggers the property changed event, so about the only time to use the property is if you don't want that event raised).



Answered By - Servy
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing