Monday, January 14, 2013

Modern C++ - part 7

std::shared_ptr is a smart pointer
which uses reference counting to keep
track of people who maintain hot
reference to a single object.The
underlying object is destroyed when
the last remaining shared_ptr pointing
to it is destroyed or
reset

The following code demonstrates the
usage of shared_ptr

//////////////////////////////////////////
// shared_ptr.cpp
//
// This program demonstrates shared_ptr
// smart pointer in C++ 11
//
// cl /EHsc shared_ptr.cpp
// g++ shared_ptr.cpp -std=c++0x
//

#include <iostream>
#include <memory>
#include <stdio.h>


////////////////////////////////////////
// Even If you pass shared_ptr<T> instance
// by value, the update is visible to callee 
// as shared_ptr<T>'s copy constructor reference
// counts to the orgininal instance
// 

void foo_byvalue(std::shared_ptr<int> i)
{
    printf("%p\n",&i);
    (*i)++;
}

///////////////////////////////////////
// passed by reference,we have note  
// created a copy.  
//
void foo_byreference(std::shared_ptr<int>& i)
{
    printf("%p\n",&i);
    (*i)++;
}
 
//////////////////////////////
//
// Entry Point...
//
int main(int argc, char **argv )
{
    auto sp = std::make_shared<int>(10);
    //////////////////
    //
    // print the address of shared_ptr instance   
    printf("%p\n",&sp);


    foo_byvalue(sp);
    foo_byreference(sp);

    //--------- The output should be 12
    std::cout << *sp << std::endl;
}



The output of my console is given below

G:\GODEL\LLVM\example>cl /EHsc shared_ptr.cpp
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

shared_ptr.cpp
Microsoft (R) Incremental Linker Version 10.00.30319.01
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:shared_ptr.exe
shared_ptr.obj

G:\GODEL\LLVM\example>shared_ptr
0037FEC4
0037FEAC
0037FEC4
12

G:\GODEL\LLVM\example>g++ shared_ptr.cpp -std=c++0x

G:\GODEL\LLVM\example>a
0028fefc
0028ff08
0028fefc
12

G:\GODEL\LLVM\example>




 

No comments: