I have a class called Array2D with a copy-constructor Array2D(const Array2D&)
. I had the problem that my program would stop whenever the copy-constructor was called. The constructor was:
Array2D(const Array2D& arr) {
Array2D(arr.rows, arr.cols); //Sets the variables cols and rows and
//sets a pointer T* ptr = new T[rows*cols]
for(size_t i = 0; i < rows*cols; i++)
ptr[i] = arr.ptr[i];
}
I moved the call for the other constructor to the contructor list:
Array2D(const Array2D& arr)
: Array2D(arr.rows, arr.cols) {
for(size_t i = 0; i < rows*cols; i++)
ptr[i] = arr.ptr[i];
}
Could anyone tell me why the second version of the code works and the second one doesn't?
PS: This is the constructor that is called from the copy constructor.
Array2D(size_t r, size_t c)
: rows(r), cols(c), ptr(new T[r*c]) {}
In
Array2D(const Array2D& arr) {
Array2D(arr.rows, arr.cols); //Sets the variables cols and rows and
//sets a pointer T* ptr = new T[rows*cols]
for(size_t i = 0; i < rows*cols; i++)
ptr[i] = arr.ptr[i];
}
Array2D(arr.rows, arr.cols);
is basically a non-op. It creates a temporary Array2d
and then it gets destroyed. This means ptr
is never initialized and using it is undefined behavior .
With
Array2D(const Array2D& arr)
: Array2D(arr.rows, arr.cols) {
for(size_t i = 0; i < rows*cols; i++)
ptr[i] = arr.ptr[i];
}
You use a delegating constructor to initialize the member variables and then you set the array elements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.