Search code examples
c++pointersmemory-managementreferenceclass-instance-variables

Is the initialization with the pointers of class instance the only one in C++?


We all know, that the simplest way to define a new instance in C++ is the next:

ClassName *obj = new ClassName();

But such a way is bad and more advanced people use smart pointers like: shared_ptr, unique_ptr etc... But if to look at their sources you may find that smart_pointers are using pointers for the creating new instances, not references.

Also I know, that using pointers is not only a bad stuff for a clean source code in C++ (design rules), but also pointers do allocate new memory, because any pointer is a void* type. The correct size depends on CPU architecture, but for the example let's take x86, it holds 4 bytes.

It's rather expensive to use, than using references &, which don't require any memory allocations for them, and that's why to use references in C++ self-defined methods is miles better.

So telling you all this info, I wonder:

Is it possible to define a new instance with a reference in C++ or not? If no, then why?


Solution

  • I am afraid your post is one misconception after another. So the first thing you have to do is throw away all the "books" you've read and read a good book on C++

    Now, to try to answer your question. You cannot create an object "with reference". It's the other way around - you can create a reference to an existing object.

    MyClass myobject;
    MyClass& myreference = myobject;
    

    Just like you can create a pointer to point to an existing object (or not point to anything). Do note that it's not the pointer that created the object. The new-expression does:

    new MyClass;
    

    created a new object of MyClass type "on the heap", if you will. But it's quite useless since you've lost all handles to it. You cannot access it. That's why we store the address of this object (which new returns) in a pointer. If it's a smart pointer instead of a plain one, it will automatically "know" when to free the memory, i.e. delete the object, depending on the type of the smart pointer. This said, you can, instead of storing the address of the newly created object, create a reference to it:

    MyClass& ref = *new MyClass;
    ...
    delete &ref;
    

    It is also not true that references come for free (in terms of memory). Sure, sizeof(reference) will return the size of the object referred to, but most implementations will use pointer-like logic for references underneath the hood.