mardi 4 février 2020

how to use memcpy with unique_ptr

I was trying to learn smart pointer as i came across this.

{ //Example 1
    //String to be copied
    std::string strHello = "HelloWorld1";
    int size = strHello.length();

    //Creating Ptr using make_unique
    std::unique_ptr<char[]> pstrText;
    pstrText = make_unique<char[]>(size + 1); // Allocating +1 for \0

    //Copying values to the new pointer
    int r = memcpy_s(pstrText.get(), size + 1, strHello.c_str(), size);

    //Printing
    std::cout << pstrText.get() << std::endl;
}

{ //Example 2
    //String to be copied
    std::string strHello = "HelloWorld2";
    int size = strHello.length();

    //Creating Ptr using make_unique
    std::unique_ptr<char[]> pstrText;
    pstrText = make_unique<char[]>(size);

    //Copying values to the new pointer
    int r = memcpy_s(pstrText.get(), size, strHello.c_str(), size);

    //Printing
    std::cout << pstrText.get() << std::endl;
}
{//Example 3

    //String to be copied
    std::string strHello = "HelloWorld3";
    int size = strHello.length();

    //Creating Ptr using make_unique
    std::unique_ptr<char[]> pstrText;
    pstrText = make_unique<char[]>(size + 1); //Allocating + 1

    //Copying values to the new pointer
    int r = memcpy_s(pstrText.get(), size, strHello.c_str(), size);

    //Printing
    std::cout << pstrText.get() << std::endl;
}

{//Example 4

    //String to be copied
    std::string strHello = "HelloWorld4";
    int size = strHello.length();

    //Creating Ptr using make_unique
    std::unique_ptr<char[]> pstrText;
    pstrText = make_unique<char[]>(size);

    //Copying values to the new pointer
    int r = memcpy_s(pstrText.get(), size + 1, strHello.c_str(), size); 

    //Printing
    std::cout << pstrText.get() << std::endl;
}

The Output is as Follows using VS 2013 Debug(Win32):

HelloWorld1
HelloWorld2²²²²½½½½½½½½■
HelloWorld3
HelloWorld4²²²²½½½½½½½½■
  1. If Example 1 is correct why does the Example 3 also give the correct output?
  2. What Does the garbage values at the end signify?
  3. Why didn't the compiler throw any error or exception?
  4. In Example 4 Why is there no error when we had tried to copy a value at the end but was not initialized
  5. How do we properly initialize a smart pointer in this case? Will anything change if it a BYTE array instead of char;

Aucun commentaire:

Enregistrer un commentaire