We all know, that the simplest way to define a new instance in C++ is the next:
ClassName *obj = new ClassName();
No, we don't... because it's not.
To create a new instance of type ClassName
, simply write:
ClassName obj;
Only use dynamic allocation when you need to!
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)
Which design rules? There are no "rules", only different sets of guidelines written by different people, all with their own views.
I would generally advise avoiding using pointers, because their use implies dynamic allocation, which is more difficult to manage. Smart pointers do help with this, but they are not a reason to use dynamic allocation where you otherwise would not.
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.
Well, that's not true either. Each pointer type is its own type, and they are not necessarily all the same width. Usually, though, this can be the case.
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.
Nope, also not true. Reference syntax in C++ hides dereference operations by performing them transparently, but you'll find that all implementations/toolchains/compilers implement references using pointers anyway.
You should stop thinking about "pointers" versus "references". Perhaps you're thinking of Java.
You should think of automatic storage duration ("the stack") vs dynamic storage duration ("the heap") — the former is more efficient as it does not require dynamic allocations, but you lose the ability to finely control the lifetime of your object.
Is it possible to define a new instance with a reference in C++ or not? If no, then why?
If by this you mean "how do I create an object without dynamic allocation", refer to the below example:
// automatic storage duration - cheap!
ClassName obj;
// dynamic storage duration - marginally more expensive,
// and now you have to `delete` it, too
ClassName* ptr = new ClassName;
In C++, a reference is like an "automatic pointer"; it does the same job, but without all the syntax requirements:
ClassName* ptr = &obj; // a pointer to obj
ClassName& ref = obj; // a reference to obj
The new
operator always gives you a pointer to the dynamically-allocated object, never a reference. This is just the way it is.