The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Lecture/Lab #20
Smart pointers (cont.): unique_ptr, shared_ptr
What will be the output of the following program?
void bar( int* ptr ) {
*(ptr + 2) = 33;
*(ptr + 4) = 55;
}
int main() {
int a[10] = { 0, 0, 0, 0, 0,
0, 0, 0, 0, 0 };
bar( a );
for ( auto n : a )
std::cout << n << " ";
std::cout << std::endl;
int* b = new int[5]();
bar( b );
for ( auto n : b )
std::cout << n << " ";
std::cout << std::endl;
int* c = new int( 42 );
bar( c );
std::cout << *c << std::endl;
}
widget* w = new widget();
// ...
delete w;
auto w = std::make_unique<widget>();
// ...
Fix compilation/run-time problems according to the expressed intent of the code and following modern C++ guidelines
Open the exercise template
Write your code, press Run to test
When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)
Click on the corresponding option in the "Lab20 exercises" poll in #general
Shared object ownership
widget* w = new widget();
foo( w );
widget* w2 = w;
// ...
if ( no_one_uses )
delete w;
auto w = std::make_shared<widget>();
foo( w );
auto w2 = w;
// ...
T* ptr
[control block]*
T object
reference count
weak count
other data (custom deleter, etc.)
Control block
Primary characteristics:
shared_ptr<T>