this-pointer

After using 'delete this' in a member function I am able to access other member functions. Why?

落爺英雄遲暮 提交于 2019-11-27 08:17:42
问题 I just wrote a sample program to see the behaviour of delete this class A { ~A() {cout << "In destructor \n ";} public: int a; A() {cout << "In constructor \n ";} void fun() { cout << "In fun \n"; delete this; cout << this->a << "\n"; // output is 0 this->fun_2(); // how m able to call fun_2, if delete this is called first ?? } void fun_2() { cout << "In fun_2 \n"; } main() { A *ptr = new A; ptr->a = 100; ptr->fun(); //delete this will be executed here ptr->fun_2(); //how m able to execute

std::shared_ptr of this

馋奶兔 提交于 2019-11-27 06:31:32
I am currently trying to learn how to use smart pointers. However while doing some experiments I discovered the following situation for which I could not find a satifying solution: Imagine you have an object of class A being parent of an object of class B (the child), but both should know each other: class A; class B; class A { public: void addChild(std::shared_ptr<B> child) { children->push_back(child); // How to do pass the pointer correctly? // child->setParent(this); // wrong // ^^^^ } private: std::list<std::shared_ptr<B>> children; }; class B { public: setParent(std::shared_ptr<A> parent

Where is the 'this' pointer stored in computer memory?

萝らか妹 提交于 2019-11-27 00:46:07
问题 Where exactly is the 'this' pointer stored in memory? Is it allocated on the stack, in the heap, or in the data segment? #include <iostream> using namespace std; class ClassA { int a, b; public: void add() { a = 10; b = 20; cout << a << b << endl; } }; int main() { ClassA obj; obj.add(); return 0; } In the above code I am calling the member function add() and the receiver object is passed implicitly as the 'this' pointer. Where is this stored in memory? 回答1: Other answers have done a very

Type of &#39;this&#39; pointer

人盡茶涼 提交于 2019-11-26 06:44:49
问题 As mentioned in the title, I would like to know about the type of \'this\' pointer. I\'m working on a project and I observed that the type of \'this\' pointer is \"ClassName * const this\" on windows using VC++ 2008. Well I would want to know what is the need/requirement to make the this pointer a constant pointer. Thanks. 回答1: The type of this pointer is either ClassName * or const ClassName * , depending on whether it is inspected inside a non-const or const method of the class ClassName .