c++ - std::shared_ptr deleted when I use It on Qt -


i use shared pointers qt project when use shared pointer of qto setlayout() this:

 model->getbody()->setlayout(layouttemplate.get()); 

the function getbody() return shared_pointer :

std::shared_ptr<qwidget> maintemplate::getbody() {    return std::shared_ptr<qwidget>(ui->body); } 

this suppression causes segmentation fault, program doesn't run. used qsharedpointer instead of std::shared_pointer : same problem

why pointer deleted?

thank in advance.

smart pointers represent ownership of objects. shared_ptr in particular represents object can shared multiple entities , has live until done using it. whenever last shared_ptr pointing object destroyed, object points destroyed. proper use of shared_ptr is:

std::shared_ptr<t> ptr_a(new t); // create t , pass shared_ptr std::shared_ptr<t> ptr_b = std::make_shared<t>(); // same effect more efficient  ptr_a = ptr_b; // smart pointer smart pointer assignment (never existing raw smart) ptr_a.reset(new t);            // fine. ptr_a = std::make_shared<t>(); // same previous line. again more efficient  //... ptr_a , ptr_b go out of scope , handle deleting objects 

note in examples of reassignment, ptr_a checked reference count , deleted held object if last shared_ptr pointing it.

generally, ever want pass raw pointers smart pointers @ exact moment of creation. did pass ownership of object temporary smart pointer. after statement, temporary shared_ptr destroyed , no copy of ever made, assumed should destroy ui->body. want return body non-const reference, or not return , provide setter functions parameters.

qwidget& maintemplate::getbody() {    return ui->body; } 

if however, reason dictates body needs able outlive class (doubtful, unless questionable design decisions have been made), need make body shared_ptr , return value. create copies of shared_ptr , guaranteed last 1 of them destroy object. must never use raw pointer after body's construction , must not manually try delete it.

ui {    // whatever class maintemplate::ui points private:     std::shared_ptr<<qwidget> body; ... }  maintemplate { public:     std::shared_ptr<qwidget> maintemplate::getbody()     {         return ui->body;     } } 

again, don't think needed if classes have been defined in practical way. also, make ui shared_ptr if not belong class, , return instead of body. then, let caller access body through returned shared_ptr.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -