Lucas Kreutz
Lucas Kreutz

Reputation: 469

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);
}

Upvotes: 13

Views: 22233

Answers (3)

mumu
mumu

Reputation: 307

Call the get() member function of std::shared_ptr<int> to get the address you want.

Upvotes: 1

fatihk
fatihk

Reputation: 7919

Here, the main trick is that equality operator (=) for shared pointers are defined in such a way that when you do:

std::shared_ptr<int> j = i;

j will not be a complete copy of i. but it will just keep the same raw pointer the shared pointer i holds and therefore, their addresses will be different.

Upvotes: 0

cgmb
cgmb

Reputation: 4424

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!
}

Upvotes: 15

Related Questions