Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I can take address of *v.begin() where v is a std::vector

#include <vector>
#include <cstdio>
using namespace std;
int f()
{
    int* a = new int(3);
    return *a;
}
int main()
{
    //printf("%p\n", &f()); 
    vector<int> v{3};
    printf("%p\n", &(*(v.begin())));
}

I cannot take address of the f(), If I comment "printf("%p\n", &f()); " out I will get error: lvalue required as unary ‘&’ operand.
but how is it possible to take address of *(v.begin())? Isn’t * operator the same as a function?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The function f returns a temporary object of the type int

int f()
{
    int* a = new int(3);
    return *a;
}

You may not apply the address of operator for a temporary object.

You could returns a reference to the created dynamically object like for example

int & f()
{
    int* a = new int(3);
    return *a;
}

And in this case this call of printf written like

printf("%p\n", ( void * )&f());

will be correct.

As for this expression &(*(v.begin())) then the dereferenced operator does return a reference to the pointed object by the iterator.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading