CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2010
    Posts
    907

    Should I transfer ownerships between objects (passing arguments) using shared_ptr's?

    Code:
    void Class1::Func(shared_ptr<type1> parameter)
    {
    }
    
    or
    
    void Class1::Func(const shared_ptr<type1>& parameter)
    {
    }
    
    or
    Should I ever pass arguments/parameters to other objects using shared_ptr's or raw pointers?
    Thanks
    Jack

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Should I transfer ownerships between objects (passing arguments) using shared_ptr

    I would say that it depends on the situation. Do you have a specific use case in mind?
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  3. #3
    Join Date
    Dec 2010
    Posts
    907

    Re: Should I transfer ownerships between objects (passing arguments) using shared_ptr

    Hi laserlight,
    No, I don't. I just read a couple of articles on this. Some argued that it should be it and others not.
    Thanks
    Jack

  4. #4
    Join Date
    May 2009
    Posts
    2,413

    Re: Should I transfer ownerships between objects (passing arguments) using shared_ptr

    When you pass around a raw pointer it's a matter of definition who owns it (and must delete it eventually). Not so when you assign a raw pointer to a shared_ptr and pass around the shared_ptr. Then the shared_ptr is the owner (and will delete the raw pointer eventually). That's the advantage of shared_ptrs over raw pointers, the question of ownership is crystal clear.

    When it comes to the mode of passing a shared pointer, it's best to pass it by const reference. This avoids lots of incrementing/decrementing of the reference counter (the shared_ptr implementation uses internally).

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured