I've read before that using the this pointer in a constructor should be avoided. Generally I can understand that the object may not be entirely constructed yet, but I've never understood entirely what the potential issues are.
This SO thread mentions:
(They also deal with shared pointers, which I should be doing...)"'this' should not be used in a constructor anyways unless you know what you're doing and don't mind the limitations"
This cboard thread doesn't really have any bad things to say about the practice.
In some test code, I didn't as much as get a warning from the compiler:
g++ version 4.6.3Code:// thistest.cpp class A; class B { public:B(A *a);private:A *a_;}; class A { public:A();private:B b_;}; A::A(): b_(this){ } B::B(A *a): a_(a){ }
g++ -Wall -c thistest.cpp
For something more concrete, I have a Model class, which is more or less a fancy symbol table. I don't want to give all clients full access to the model, so I created another class, ModelReader. ModelReader can return a requested symbol from the Model, but can't do much else. I would like it if a Model could provide its own ModelReader.
Code:#include "modelreader.h" class Model { public:Model();ModelReader *reader() const;//And some other stuffprivate:ModelReader reader_;}; Model::Model() {: reader_(this){ } ModelReader *Model::reader() const {return reader_;}Are there any limitations to this approach?Code:// modelreader.h class Model; class ModelReader { public:ModelReader(Model *model);// Some other functions here to make it usefulprivate:Model *model_;}; ModelReader::ModelReader(Model *model): model_(model){ }
Are there better design alternatives?
In general, what are the limitations / caveats to using the this pointer in a constructor?
Thanks in advance



1Likes
LinkBack URL
About LinkBacks




.