My following question is on memory management. I have for example an int variable not allocated dynamically in a class, let\'s say invar1. And I\'m passing the memory addres
You can get rid of raw pointers and forget about memory management with the help of smart pointers (shared_ptr
, unique_ptr
).
The smart pointer is responsible for releasing the memory when it goes out of scope.
Here is an example:
#include
#include
class ex1{
public:
ex1(std::shared_ptr p_intvar1)
{
ptoint = p_intvar1;
std::cout << __func__ << std::endl;
}
~ex1()
{
std::cout << __func__ << std::endl;
}
private:
std::shared_ptr ptoint;
};
int main()
{
std::shared_ptr pi(new int(42));
std::shared_ptr objtoclass(new ex1(pi));
/*
* when the main function returns, these smart pointers will go
* go out of scope and delete the dynamically allocated memory
*/
return 0;
}
Output:
ex1
~ex1