C++: Difference between revisions

133 bytes removed ,  24 October 2019
Line 175: Line 175:
There are a few ways to do this:
There are a few ways to do this:
* Use smart pointers
* Use smart pointers
* Copy-and-swap idiom [https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom Reference]
* Swap
* Call a clear/shrink/deallocate function
* Call a clear/shrink/deallocate function
Example [https://stackoverflow.com/questions/3054567/right-way-to-deallocate-an-stdvector-object Reference]:
Example [https://stackoverflow.com/questions/3054567/right-way-to-deallocate-an-stdvector-object Reference]:
Line 183: Line 183:
my_vector.reset();
my_vector.reset();


// Copy-and-swap idiom
// Swap
std::vector<float> my_vector(99);
std::vector<float> my_vector(99);
std::vector<float>().swap(my_vector);
my_vector = std::vector<float>;
// Or alternatively
// std::vector<float>().swap(my_vector);
 


// Copy-and-swap for cl::Buffer
// Copy-and-swap for cl::Buffer
cl::Buffer my_buf(context, CL_MEM_READ_WRITE, size);
cl::Buffer my_buf(context, CL_MEM_READ_WRITE, size);
{
my_buf = cl::Buffer();
  // Moves ownership to temp
  cl::Buffer temp(my_buf);
  // or cl::Buffer temp = my_buf;
}


// Clear and shrink
// Clear and shrink