2

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?

1 Answer 1

5

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)

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

2 Comments

To be fair the debugger could (and arguably should) see this, as it potentially has more information than the C++ type system. The fact that the debugger displays the pointer type as std::string* rather than std::string[] or even std::string[5] is a debugger QOI issue.
@KonradRudolph thanks, added a note at the bottom, feel free to edite the answer if you think that there is more to say, i'll gladly approve and accept it

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.