Yesterday I took a dive into smart pointers and wasn't sure when I should use them vs. Raw pointers. I found out they are quite useful but they do not work all the time for me.
Example of working:
char* Buffer = new char; fread(buffer, 1, sizeof(buffer), infile); //took out the while loop for this example. delete Buffer; Buffer = nullptr; //Changed to: std::unique_ptr Buffer(new char); fread(buffer.get(), 1, sizeof(buffer), infile); //took out the while loop for this example. //I never have to do delete correct?
In the above, I had to use .get() to pass my pointer to fread and various other functions. My problem comes when I try to do:
//Raw ptr works well.. char* pFile; char* pMemory = new char[SomeSize]; pFile = pMemory; memcpy(pFile, Buffer, dwHeader); pFile = (char*)((DWORD)pFile + jmpSize); //Smart ptr.. :S I'm confused.. std::shared_ptr<char> pMemory(new char[SomeSize]); std::shared_ptr<char> pFile(pMemory); //The same as pFile = pMemory? Also had to declared pFile after pMemory. memcpy(pFile.get(), Buffer, dwHeader); pFile.get() = (char*)((DWORD)pFile.get() + jmpSize); //Errors :S
How do I assign to my ptr? Is is supposed to be shared or unique? I know unique uses move semantics so only one can owner can have the raw ptr. So I used shared since that's what the equal sign does right?
Is there any moment in time where I should use a Smart pointer vs. a Raw pointer (Referring to a bitmap class where there is a member pointer to a struct that is deleted in the destructor).
Edited 4 Years Ago by triumphost