Search code examples
c++pointerssmart-pointers

How to get smart pointers' address


In the following code, should the & operator return the address of the smart pointer allocation, or the address of the pointer it's controlling?

main() {
    std::shared_ptr<int> i = std::shared_ptr<int>(new int(1));
    std::shared_ptr<int> j = i;
    printf("(%p, %p)\n", &i, &j);
}

Running the code, I got different addresses. If I run an equivalent code with raw pointers, I get the same address:

main() {
    int e = 1;
    int *k = &e;
    int *l = k;

    printf("(%p, %p)\n",k,l);
}

Solution

  • In the first example, you're getting the address of the smart pointer object. The raw pointer contained within a smart pointer is provided via the get() function.

    The address-taking of smart pointers works almost exactly the same as regular pointers, actually. The raw pointer equivalent of your first example would be this:

    main() {
        int e = 1;
        int *k = &e;
        int *l = k;
    
        printf("(%p, %p)\n",&k,&l); // now they're different!
    }
    

    And the smart pointer equivalent of your second example would be this:

    main() {
        std::shared_ptr<int> i = std::shared_ptr<int>(new int(1));
        std::shared_ptr<int> j = i;
        printf("(%p, %p)\n", i.get(), j.get()); // now they're the same!
    }