User Tools

Site Tools


home:computing:programming_langs:c:are_references_safer_than_pointers

[up]

are references safer than pointers?

struct A
{
    A(int& a)
        : m_a(a)
    {}
 
    void print()
    {
        std::cout << m_a << std::endl;
    }
 
    int& m_a;
};
 
int main(int argc, char* argv[])
{
    int* b = new int();
    *b = 1234567890;
 
    A a(*b);
    a.print();
 
    *b = 43210;
    a.print();
 
    delete b;
    a.print();
 
    return 0;
}

prints the following:

1234567890
43210
-572662307
home/computing/programming_langs/c/are_references_safer_than_pointers.txt · Last modified: 18:55 18/07/2025 by acz

Except where otherwise noted, content on this wiki is licensed under the following license: Public Domain
Public Domain Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki