c++ - Doesn't get() break the idea behind std::unique_ptr? -


example code:

#include<memory> #include<iostream>  int main() {   std::unique_ptr<int> intptr{new int(3)};    int* myptr = intptr.get();    *myptr = 4;    std::cout<<"new result intptr: "<< *intptr.get()<<std::endl;  } 

doesn't defeat whole purpose behind std::unique_ptr ? why allowed?

edit: thought whole purpose behind std::unique_ptr have sole ownership of object. example, object can modified through pointer. doesn't defeat std::unique_ptr's purpose?

while smart pointers manage lifetime of object being pointed to, still useful have access underlying raw pointer.

in fact if read herb sutter's gotw #91 solution: smart pointer parameters recommends passing parameters pointer or reference when function agnostic lifetime of parameter, says:

pass * or & accept widget independently of how caller managing lifetime. of time, don’t want commit lifetime policy in parameter type, such requiring object held specific smart pointer, because needlessly restrictive.

and should pass unique_ptr when function sink:

passing unique_ptr value possible moving object , unique ownership caller callee. function (c) takes ownership of object away caller, , either destroys or moves onward somewhere else.

and pass unique_ptr reference when can potentially modify refer different object:

this should used accept in/out unique_ptr, when function supposed accept existing unique_ptr , potentially modify refer different object. bad way accept widget, because restricted particular lifetime strategy in caller.

of course, required underlying pointer if have interface c libraries take pointers.

in specific example:

int* myptr = intptr.get(); 

there no transfer of ownership smart pointer there no problems long don't attempt delete pointer via myptr. can transfer ownership unique_ptr moving it:

std::unique_ptr<int> intptr2( std::move( intptr ) ) ; 

Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -