You are right, x[0] = ca
will perform copy-assignment, which apparently is not what you want.
You are close in your pointer example, but you instead need to get the address of ca
:
CArray *x[16];
x[0] = &ca;
However, you must be very careful to manage the lifetime of ca
properly lest it goes out of scope prematurely.
You may want to look into using smart pointers.
Edit: Given your comment on the other answer
"Isn't there a system that makes that the array will exist until there are no reference anymore for it? (I'm coming from Python, which garbage collector!"
Yes, like I mentioned before, you may want to use smart pointers. You could begin with std::unique_ptr
if x
will be the sole owner:
std::unique_ptr<CArray> x[16];
Will create an array of 16 unique pointers that will go out of scope after they are no longer being referenced. Here's how you could assign:
x[0] = std::make_unique<CArray>();
If you want other objects to participate in the lifetime of the memory (that is, the memory will not be deallocated until multiple people are finished referencing it), the process is much the same to use a shared_ptr
:
std::shared_ptr<CArray> x[16];
x[0] = std::make_shared<CArray>();
Shared pointers are easier to work with because they're readily copied, but you pay a bit of cost in time and space overhead.