Can we use 'this' pointer inside constructor [duplicate]

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-01 04:24:25

问题


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.



来源:https://stackoverflow.com/questions/12071147/can-we-use-this-pointer-inside-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!