Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ smart pointers address

I am a little confused with smart pointers. In the following code, should the & operator return the adress 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 address. If I run an equivalent code with raw pointers, I get the same adress:

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

    printf("(%p, %p)\n",k,l);
}
like image 384
Lucas Kreutz Avatar asked May 24 '13 04:05

Lucas Kreutz


People also ask

What is the address of a pointer in C?

The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the architecture.

What is a smart pointer in C?

A Smart Pointer is a wrapper class over a pointer with an operator like * and -> overloaded. The objects of the smart pointer class look like normal pointers. But, unlike Normal Pointers it can deallocate and free destroyed object memory.

Are there smart pointers in C?

Smart Pointers in C++ Smart pointer in C++, can be implemented as template class, which is overloaded with * and -> operator.

How do I find the address of my pointer?

To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x.


1 Answers

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!
}
like image 200
cgmb Avatar answered Sep 30 '22 01:09

cgmb