Can we use 'this' pointer inside construct

2019-03-25 06:03发布

问题:

Possible Duplicate:
C++ using this pointer in constructors

Like the title, may I do something like the following code?

class A;

class B {
public:
    B(A* p);
    ...
};

class A {
    B m;
public:
    A():m(this){}
    ~A(){}
};

回答1:

Yes, you can passed a pointer to an object currently under construction. But you have to keep in mind, that the object isn't constructed completely yet. So basically what B can do in it's c'tor is store the pointer for later use.

An example where this is often used, is a std::stream and a stream buffer.



标签: c++ class