Trying to use best practices for C++ and I see that you should be using std::unique_ptr now. And coming from using raw pointers only I have some questions.
When it comes to returning functions, if I return a std::unique_ptr like:
//Declared as member variable of MyObject class
std::unique_ptr<InternalObject> internalObject;
//Return function of MyObject class to get internalObject as a std::unique_ptr
std::unique_ptr<InternalObject> getInternalObject() {
return internalObject;
}
What am I really returning here? I read that this more or less “gives up” ownership of the pointer and does std::move. If this is true what happens to my internalObject variable?
Assuming the above is true still. If I don't want to transfer ownership I assume I do this instead
//Declared as member variable of MyObject class
std::unique_ptr<InternalObject> internalObject;
//Return function of MyObject class to get internalObject as pointer
InternalObject* getInternalObject() {
return internalObject.get();
}
This kind of seems wrong because I though the whole point of smart pointers like std::unique_ptr was so you don't touch/handle the raw pointer. Because couldn't I just do something like
//Declared as member variable of MyObject class
std::unique_ptr<InternalObject> internalObject;
//Return function of MyObject class to get internalObject as pointer
InternalObject* getInternalObject() {
return internalObject.get();
}
//Somewhere in my program
MyObject myObject;
InternalObject* value = myObject.getInternalObject();
delete value;
What is the proper way I should be using / returning std::unique_ptr?
Also I noticed that you cannot do things like
//Internal Object
class InternalObject
{
private:
InternalObject();
~InternalObject();
}
//Inside MyObject class
std::unique_ptr<InternalObject> createInternalObject() {
//Compiler Error: Mad about private destructor?
return std::unique_ptr<InternalObject>(new InternalObject());
}
So how should you be working with std::unique_ptr when I want to declared constructor/destructors as private?