CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2002
    Posts
    788

    assign auto_ptr to unique_ptr

    I have a function who return an auto_ptr to me and i wish to assign this pointer to a unique_ptr in my class member variable.

    Code:
    class Data
    {
    ....
    void Run();
    private:
    std::unique_ptr<Test> p_testUnique;
    
    }
    
    void Data::Run()
    {
    std::auto_ptr<Test> testPtr = GetTest();
    std::unique_ptr testPtrUnique(testPtr .get());
    p_testUnique = std::move(testPtrUnique);
    
    }
    Is the above correct? So now there are two pointers, testPtr and p_testUnique, both pointing to the same data returned from GetTest?

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

    Re: assign auto_ptr to unique_ptr

    I think you should use auto_ptr's release rather than get.
    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
    Oct 2008
    Posts
    1,456

    Re: assign auto_ptr to unique_ptr

    or you could simply write

    Code:
    void Data::Run()
    {
    	p_testUnique = GetTest();
    }
    indeed, unique_ptr has an implicit constructor from an rvalue of auto_ptr type ( that calls release() internally ); in turn, the resulting temporary unique_ptr is move assigned to your member variable.
    Of course, nothing stops you from being more explicit if needed ...

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