I am working on a school project and I cannot figure out unique_ptr usage.
class ClassName
{
private:
unique_ptr <bool[]> uniquePtr;
void func(unique_ptr<bool[]>& refPtr) const
{
refPtr[0] = true;
refPtr[1] = false;
}
public:
//other things that will use the array uniquePtr
};
ClassName::ClassName()
{
bool* boolName = new bool [someSize()];
uniquePtr = unique_ptr<bool[]>(boolName);
func(uniquePtr);
for(int i =0; i<someSize(); i++)
{
cout << uniquePtr[i];
//This is all O's
}
}
This does not work because uniquePtr is set to all 0s as func() finishes. I cannot figure out how to modify uniquePtr such that it will be accessible to my other functions. I do not have tried creating a new unique_ptr to pass into func() and then use move(uniquePtr) but that won't even compile.
If the uniquePtr is modified by a function, in this case assigning it boolean 1 or 0, shouldnt it be accessible to function outside of that in the class? If I print uniquePtr[index] within the function it gives me the expected results.
Thanks for the help!
uniquePtris a non-static member, so its lifetime is connected to the lifetime of theClassNameobject. What specific trouble are you having that makes you conclude "this does not work"?funcWhy does it have to be non-static? Why does it have to beconstqualified? Why do you need to pass the pointer to the function as an argument? Can't you simply use it like any other normal member variable?