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[1024];
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[1024]);
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

Questions:
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).

Smart pointers are not meant to point to dynamic arrays, but to individual objects. Boost has a shared_array class to deal with arrays, but I wouldn't recommend it.

In your case, you should be allocating your dynamic arrays using an STL container, in particular, std::vector. As so:

std::vector<char> Buffer(1024);
fread(&Buffer[0], 1, Buffer.size(), infile);
// no need to delete anything, Buffer will go out-of-scope and clear the memory automatically.

As for the other example (with memcpy), you should learn to work with iterators and STL algorithms. Below is the code that is equivalent to yours:

std::vector<char> pMemory(SomeSize);
std::vector<char>::iterator pFile = pMemory.begin();
std::copy(pBuffer.begin(), pBuffer.begin() + dwHeader, pFile);
pFile += jmpSize;

Think of iterators like they were pointers (but not necessarily actual pointers).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.