KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I want to pass a unique_ptr to a helper function, and I want to make sure that the helper function neither modifies the pointer, nor the pointed object. Without the unique_ptr , the solution is to have void takePtr(AClass const * const aPtr) { // Do something with *aPtr. // We cannot change aPtr, not *aPtr. } (Well, technically, AClass const * aPtr is enough.) And I can call this with AClass * aPtr2 = new AClass(3); takePtr(aPtr2); I want to instead use unique_ptr , but cannot figure out how to write this. I tried void takeUniquePtr(unique_ptr<AClass const> const & aPtr) { // Access *aPtr, but should not be able to change aPtr, or *aPtr. } When I call this with unique_ptr<AClass> aPtr(new AClass(3)); takeUniquePtr(aPtr); it does not compile. The error I see is testcpp/hello_world.cpp:141:21: error: invalid user-defined conversion from ‘std::unique_ptr<AClass>’ to ‘const std::unique_ptr<const AClass>&’ [-fpermissive] Shouldn't the conversion from unique_ptr<AClass> to unique_ptr<AClass const> be automatic? What am I missing here? By the way, if I change unique_ptr<AClass const> const & aPtr to unique_ptr<AClass> const & aPtr in the function definition, it compiles, but then I can call functions like aPtr->changeAClass() , which I don't want to allow.
Tags (comma-separated)
Save Edits
Cancel