0

So I am trying to change my game and I found a problem where I couldn't make the change:

I have the following code:

    std::string fileContents = "";
  const char* contentsPtr = fileContents.c_str();

I tried making it:

const std::unique_ptr<char> contentsPtr = fileContents.c_str();

It doesn't work since there is no constructor to make the conversion from char* to unique_ptr so how can I make this change?

7
  • 4
    The pointer returned by c_str() is not up for grabs, it's owned by fileContents. You can't just shove it in a unique_ptr and let it own it. Why do you even think you need a unique_ptr in your case? Commented Nov 11, 2018 at 11:01
  • 2
    In that case, why have contentsPtr at all? What does your code use it for? Commented Nov 11, 2018 at 11:10
  • 1
    @Ninhow Explain what you really need to do. Why are you not supposed to use naked pointers? It's error-prone? It's inefficient? It looks ugly? It's hard to understand? Commented Nov 11, 2018 at 11:14
  • 1
    @Ninhow - That's not a bad goal in general. But one should not be going about it by way of cargo cult programming. Commented Nov 11, 2018 at 11:15
  • 2
    The question to ask is who owns the data. In this case it's fileContents. Smart pointers own the data and you cannot have more than one owner. Multiple shared pointers can share ownership with each other, but not with something else. You may want to watch youtu.be/JfmTagWcqoE Commented Nov 11, 2018 at 11:27

1 Answer 1

5

You do not want a unique_ptr around any resource you do not own. In this case the pointer returned from c_str(). It still belongs to fileContents objects. If/when you get past actually getting a unique_ptr around c_str(), then you later have memory corruption.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.