Ask coding questions

← Back to all posts
memcpy into shared_ptr doesn't fully copy?
xxpertHacker (855)

The attached Repl should copy the text "Hello, world!" into an instance of a SharedString, and then print it.

It only prints "Hello, w" though... and I can't tell why.

(Excuse the code formatting, I'm on Repl mobile)

Answered by DynamicSquid (4631) [earned 5 cycles]
View Answer
DynamicSquid (4631)

Your shared_ptr isn't correct. I found this SO answer that might help.

xxpertHacker (855)

@DynamicSquid Are you suggesting that I use the new operator and pass in the pointer?

DynamicSquid (4631)

@xxpertHacker You have to store it as a char[], then pass in a char* in the shared_ptr constructor. No using make_shared.

xxpertHacker (855)

@DynamicSquid >_< that is totally wrong, lol.

But I realized that I did misuse make_shared, I double checked docs and read some parenthesis as brackets. Fixing shared_ptr usage right now.

I needed a C++20 compiler to have used that code.

DynamicSquid (4631)

@xxpertHacker Wait what I though make_shared didn't accept arrays?

xxpertHacker (855)

@DynamicSquid Depends, as a template argument or call argument?

Overload 2, C++20.

I'm still looking for how this was done back in C++17 :(

DynamicSquid (4631)

@xxpertHacker Huh, never considered that before

xxpertHacker (855)

@DynamicSquid Ah, okay, C++14 had the overload that I wanted but for make_unique :/

Very annoying, seems like I need to use new.