Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat is the proper way to write C++ Setters for members which are pointers to other objects so that there are no memory leaks or crashes?
    primarykey
    data
    text
    <p>I have searched a lot on this. But may be I am not getting the phrasing right. </p> <p>Consider, </p> <pre><code>Class A {}; Class B { public: A* getA(); void setA(A *aVarParam); private: A *aVar; }; </code></pre> <p>Now since aVar is a member variable of class B I want to ensure that it stays alive as long the corresponding object of class B exists. </p> <p>So the options I see here are, </p> <ol> <li>Make a deep copy of aVarParam and hold a pointer to it.</li> <li>Use something like a Boost shared pointer. </li> </ol> <p>Both of which seems either too much work or ugly syntax. Am I missing something here? Do all C++ programs use one of these 2 options? </p> <p>More Explanation:</p> <p>Ok many of you wanted to see an example of how I am using it. Actually I wanted a general purpose strategy kind of answer. Hence the original example. Here is the example I am trying to use:</p> <pre><code>#ifndef DBSCHEMA_H #define DBSCHEMA_H #include &lt;string&gt; #include &lt;vector&gt; #include "dbtable.h" namespace models { class DbSchema { public: explicit DbSchema(); boost::shared_ptr&lt;std::string&gt; getSchemaName() const; void setSchemaName(const boost::shared_ptr&lt;std::string&gt; schemaName); std::vector&lt;models::DbTable&gt; getTableList() const; void setTableList(const std::vector&lt;models::DbTable&gt; tableList); private: boost::shared_ptr&lt;std::string&gt; schemaName_; std::vector&lt;models::DbTable&gt; tableList_; }; } #endif // DBSCHEMA_H </code></pre> <p>Here the class DbSchema is being used as a thin model which will direct the UI (A QT application). And there will be many Schema Builders which will actually communicate with different databases to fill the DBSchema objects which the UI will use.</p> <p>I hope this clears up about what I am trying to achieve. I am not a C++ programmer. After programming Java, Objective-C, PHP and JavaScript for years, I am trying to satisfy an itch to write a "real C++" application. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload