Search code examples
c++arrayssmart-pointers

Create an array of objects using std::unique_ptr


I am currently learning smart pointers and am trying to do the following:

#include <memory>
#include <string>

int main() {
    std::unique_ptr<std::string[]> str_array(new std::string[5]);
    for (int i = 0; i < 5; i++) {
        std::getline(std::cin, str_array.get()[i]);
    }
    return 0;
}

This code simply scans 5 std::string objects into an array. However, the debugger shows that the memory is not getting reserved for 5 objects:

the debugger

What am I doing wrong?


Solution

  • It's caused by the fact that new std::string[5] is a dynamic array allocation, and so it has no (fixed/defined/calculable) size (if you don't save it before the allocation), infact

    auto p = new std::string[5];
    std::cout << sizeof(p);
    

    Will print 8 that is the size of a pointer.

    And so the debugger sees that ptr as a pointer, and can't figure out that there are other 4 elements after the first one (and so can't figure out that is an array, and not just a pointer to a string)

    Seems like that this is a "C++ POV", and that the debugger can have more informations, and so should be able to figure out that it is an array of string and not just a pointer to string (thanks to @Konrad Rudolph)