Last active
December 24, 2022 03:41
-
-
Save loneshark99/e3d1d88a700a094d4c3b813b46d51a08 to your computer and use it in GitHub Desktop.
C++ Dont Create Copies Pass by Reference as it affects performance.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "Array.hpp" | |
Array::Array() | |
{ | |
std::cout << "CONSTRUCTOR CALLED" << std::endl; | |
for (auto i = 0; i < 100000; i++) | |
{ | |
data.push_back(i*i); | |
} | |
} | |
Array::Array(const Array& rhs) | |
{ | |
std::cout << "COPY CONSTRUCTOR CALLED" << std::endl; | |
data.clear(); | |
for (auto i = 0; i < 100000; i++) | |
{ | |
data.push_back(rhs.data[i]); | |
} | |
} | |
Array& Array::operator=(const Array& rhs) | |
{ | |
std::cout << "COPY Assignment Operator CALLED" << std::endl; | |
if (&rhs == this) | |
{ | |
return *this; | |
} | |
data.clear(); | |
for (size_t i = 0; i < rhs.data.size(); i++) | |
{ | |
data.push_back(rhs.data[i]); | |
} | |
return *this; | |
} | |
void Array::PrintArray() | |
{ | |
for (auto i = 0; i < data.size(); i++) | |
{ | |
std::cout << data[i] << std::endl; | |
} | |
std::cout << "******************************" << std::endl; | |
} | |
void Array::SetData(int index, int value) | |
{ | |
data[index] = value; | |
} | |
Array::~Array() | |
{ | |
//delete[] data; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef ARRAY_HPP | |
#define ARRAY_HPP | |
#include <vector> | |
class Array | |
{ | |
public: | |
Array(); | |
Array(const Array& rhs); | |
// Copy Assignment Operator | |
// Object is already constructed we are just making a copy later... | |
Array& operator=(const Array& rhs); | |
void PrintArray(); | |
void SetData(int index, int value); | |
~Array(); | |
private: | |
std::vector<int> data; | |
}; | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "Array.hpp" | |
void PrintArray(const Array& a) | |
{ | |
//a.PrintArray(); | |
} | |
int main() | |
{ | |
// Copy Constructor | |
Array myArray; | |
myArray.SetData(0,1234567); | |
// Copy Assignment Operator | |
// Array myArray2; | |
// myArray2 = myArray; | |
// Copy Constructor is called. | |
Array myArray2 = myArray; | |
//myArray.PrintArray(); | |
//myArray2.PrintArray(); | |
for (size_t i = 0; i < 100; i++) | |
{ | |
PrintArray(myArray); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment