I was told not to use pointers in C ++. It seems that I cannot avoid them, however, in the code I'm trying to write, or maybe I am missing out on other great C ++ features.
I want to create a class (class1) that contains another class (class2) as a data member. Then I want class2 to know about class1 and be able to communicate with it.
I could refer to class1 as a member in class2, but that means I need to provide a reference to class1 as a parameter in the constructor of class2 and use initializer lists that I don't want. I am trying to do this without requiring a constructor to do this.
I would like class2 to have a member function called Initialise that could take a reference to class1, but this seems impossible without using pointers. What would people recommend here? Thanks in advance.
The code is completely simplified to get the basic idea:
class class1 { public: InitialiseClass2() { c2.Initialise(this); } private: class2 c2; }; class class2 { public: Initialise(class1* c1) { this->c1 = c1; } private: class1* c1; };
this seems impossible without using pointers
This is not true. Indeed, to process a link to some other object, take the link into the constructor:
class class2 { public: class2(class1& c1) : c1(c1) {} private: class1& c1; };
- , . , , Initialise RAII (, !). , , ; , smart-pointer — a std::weak_ptr.
Initialise
std::weak_ptr
, .
"" ? , , . , "" , .
? .
, , , - .
, ++ , - . - , .
, . - . ++ . , .
nullptr, - ( - ).
nullptr
.
std::shared_ptr std::unique_ptr .
std::shared_ptr
std::unique_ptr
, 2 , , ? - , 2 , , , ). :
, - . ;)
. , , ( , , , , , , ). "" , , , .
, , , , . , .
++. , , , , , , , ++.
- . ++ ( ), , . ++ , , . , . , .
, , raw , . , , , , / , .
( ) , , . , , ( /= ), . - , , ( ).
Source: https://habr.com/ru/post/1611797/More articles:Qt 5.5 QOpenGLTexture copying data - c ++Return state does not work in Java - javaResume scroll position after stopping scroll - javascriptAndroid NFC: исключение "transceive failed" при использовании transceive() - androidRegular expressions in Excel VBA - vbaRegular expression in Excel VBA - part two - vbaHow to bring the figure legend to the front? - pythonPython 3.5 - the name "wait" is undefined - pythonJsDoc, ES6 and @param {Constructor} - javascriptChart structure - bad pointers? - c ++All Articles