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);
}
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.
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.
Smart Pointers in C++ Smart pointer in C++, can be implemented as template class, which is overloaded with * and -> operator.
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.
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!
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With