CUDA Networks
matrix_copy.cu
Go to the documentation of this file.
1 /**
2  * @file matrix_copy.cu
3  * @brief Implementation of copy and move operations for the Matrix class.
4  */
5 
6 #include "matrix.h"
7 #include <cuda_runtime.h>
8 
9 Matrix::Matrix(const Matrix& other) : rows(other.rows), cols(other.cols) {
10  // Allocate new memory on the device
11  cudaMalloc(&d_data, rows * cols * sizeof(double));
12  // Copy data from the other matrix to this one
13  cudaMemcpy(d_data, other.d_data, rows * cols * sizeof(double), cudaMemcpyDeviceToDevice);
14 }
15 
17  if (this != &other) { // Protect against self-assignment
18  // Free existing memory
19  cudaFree(d_data);
20 
21  // Copy dimensions
22  rows = other.rows;
23  cols = other.cols;
24 
25  // Allocate new memory
26  cudaMalloc(&d_data, rows * cols * sizeof(double));
27  // Copy data from the other matrix
28  cudaMemcpy(d_data, other.d_data, rows * cols * sizeof(double), cudaMemcpyDeviceToDevice);
29  }
30  return *this;
31 }
32 
33 Matrix::Matrix(Matrix&& other) noexcept
34  : rows(other.rows), cols(other.cols), d_data(other.d_data) {
35  // Transfer ownership and reset the source object
36  other.d_data = nullptr;
37  other.rows = 0;
38  other.cols = 0;
39 }
40 
41 Matrix& Matrix::operator=(Matrix&& other) noexcept {
42  if (this != &other) { // Protect against self-assignment
43  // Free existing memory
44  cudaFree(d_data);
45 
46  // Transfer ownership
47  rows = other.rows;
48  cols = other.cols;
49  d_data = other.d_data;
50 
51  // Reset the source object
52  other.d_data = nullptr;
53  other.rows = 0;
54  other.cols = 0;
55  }
56  return *this;
57 }
58 
60  // Use the copy constructor to create a deep copy
61  return *this;
62 }
Represents a matrix with GPU-accelerated operations.
Definition: matrix.h:18
Matrix & operator=(const Matrix &other)
Copy assignment operator.
Definition: matrix_copy.cu:16
Matrix(int rows, int cols)
Construct a new Matrix object.
Matrix copy() const
Creates a deep copy of the matrix.
Definition: matrix_copy.cu:59
Defines the Matrix class for GPU-accelerated matrix operations.