Note that there are some explanatory texts on larger screens.

plurals
  1. POInit a shared_ptr of reference ( std::tr1::shared_ptr<class&> )
    primarykey
    data
    text
    <p>I'm using a library which returns a reference to me.<br> I need to use this reference as class-attribute.<br> Not being able to initialize the attribute in constructor directly (the lib needs to be inited before), I thought about using a shared_ptr for lazy initialization:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;tr1/memory&gt; //This is library, cannot touch std::string globalString = "TEST"; std::string&amp; getStringReference() { return globalString; } //this is my class which uses the library class Foo { public: Foo() : testString_( std::tr1::shared_ptr&lt; std::string&amp; &gt;() ) { //do some initialization of the library here... //now init the shared_ptr testString_.reset( getStringReference() ); } std::string getString() const { return *testString_; } private: std::tr1::shared_ptr&lt; std::string&amp; &gt; testString_; }; //and a main to be compilable and check if the above works... int main() { Foo foo; std::cout &lt;&lt; foo.getString() &lt;&lt; std::endl; } </code></pre> <p>But unfortunately this does not work. g++ gives messages like this:</p> <pre><code>error: forming pointer to reference type ‘std::string&amp;’ </code></pre> <p>I tried some other ways to get the reference into the shared_ptr, but nothing works... Perhaps you could give me a hint.</p> <p>Note:<br> - In "real-world" instead of std::string the datatype is a class without default constructor.<br> - For those who still wonder: The above is just a simplified example-code :)</p> <p><strong>UPDATE:</strong><br> - While trying to apply the suggestions, I found out that contrary to the used std::string from example, my class has a private copy constructor. This means I'm not able to just copy the object into a new one.</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