// Example program
#include <iostream>
#include <string>
void create()
{
for(;;){
int *a = newint;
std::cout<<a<<std::endl;
delete a;
}
}
int main()
{
create();
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// Example program
#include <iostream>
#include <string>
void create()
{
for(;;){
int *a = newint;
std::cout<<a<<std::endl;
}
}
int main()
{
create();
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Example program
#include <iostream>
#include <string>
int * create()
{
int *a = newint;
return a;
}
int main()
{
for(;;){
int *a=NULL;
a=create();
std::cout<<a<<std::endl;
}
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
// Example program
#include <iostream>
#include <string>
int * create()
{
int *a = newint;
return a;
}
int main()
{
for(;;){
int *a=NULL;
a=create();
std::cout<<a<<std::endl;
delete a;
}
}
A new Foo does three operations:
1. Allocates memory from Free Store for Foo-type object.
2. Constructs Foo-type object in the allocated memory
3. Returns the address of the object
The lifetime of the object is not limited to the scope where it was created.
There is no "garbage collection"; object destruction and memory deallocation have to be done explicitly.
The deleteaddress ; does two operations:
1. Destructs the object that is at address
2. Deallocates the memory block
What does happen, if you attempt to allocate infinite bytes of memory? Two of your examples do that.
RAII:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <memory>
auto create()
{
auto foo = std::make_shared<int> (42);
return foo;
// foo goes out of scope
}
int main()
{
for(int x=0;x<10;++x){
auto bar = create(); // foo goes out of scope, but bar has a copy of pointer
std::cout << *bar << std::endl;
// bar goes out of scope; proper deallocation of the int
}
}