Take the 2-minute tour ×
void OnReceived(std::shared_ptr<uint8_t> buffer, int len) {

int main(){
std::vector<char> buffer(1000);

am trying to cast it but i cant i dont know why!!!

Error   1   error C2664: 'std::tr1::_Ptr_base<_Ty>::_Reset0' : cannot convert parameter 1 from 'char *' to 'uint8_t *'  c:\program files\microsoft visual studio 10.0\vc\include\memory 1705

so how can i convert it?

share|improve this question
Maybe (std::shared_ptr<uint8_t>)(uint8_t*)buffer.data()? –  ikegami May 25 '11 at 22:34
The point of types is for safety, of which you defeat the purpose by trying to cast anyway. You should try to understand the role of each type and solve it that way, not try to ignore them. –  GManNickG May 25 '11 at 23:10
add comment

4 Answers

up vote 4 down vote accepted

You really don't want to do that. Aside from the fact that char and uint8_t may be distinct types, even if you force the code to compile, your buffer will be deallocated twice, likely crashing your program. Just change OnReceived to accept a raw pointer.

share|improve this answer
+1 - the purpose of a smart pointer is to control object lifetime. If a function can't affect the object lifetime, it doesn't matter if you pass it a smart pointer or a dumb one, and the dumb one is easier to work with. –  Mark Ransom May 25 '11 at 22:43
add comment

Beyond the type mismatch, you don't want to do that. It'll almost cause a crash when both the vector destructor and the shared_ptr deallocate the same memory. You should consider boost::shared_array or a shared pointer to the entire vector (shared_ptr<std::vector>) instead of what you're doing now. Or as Igor suggests, OnReceived could be changed to accept a raw pointer if it doesn't need shared ownership of the buffer.

share|improve this answer
add comment

uint8_t is an unsigned char so you'll either need to change the type of buffer or reinterpret_cast somewhere along the line.

share|improve this answer
add comment

buffer.data() will return a char *. You're trying to cast that to a std::shared_ptr - in other words, construct a shared_ptr out of it. In its implementation it tries to assign the pointer but can't since you're passing in an incompatible pointer type.

Try casting it to the appropriate type before passing it in, such as:

OnReceived((std::shared_ptr<uint8_t>)(uint8_t *)buffer.data(),rcvlen);

or, probably a better solution, convert your std::vector to a vector of uint8_t.

share|improve this answer
add comment

Your Answer


