Click here to Skip to main content
Click here to Skip to main content

CAutoNativePtr - A managed smart pointer for using native objects in managed code

, 20 Jan 2006 Ms-PL
Rate this:
Please Sign up or sign in to vote.
CAutoNativePtr is a managed template class that acts as a smart pointer, and is handy for using native objects in managed code.


CAutoNativePtr is a managed template class that acts as a smart pointer, and is handy for using native objects in managed code.

  typename T
ref class CAutoNativePtr

Here, T is the native type that's wrapped. The class manages a smart pointer, which will automatically free the native resource when it falls out of scope or the containing managed object is finalized during garbage collection. The copy constructors and assignment operators transfer ownership, which means that only one CAutoNativePtr can own a specific native object at any time (unless you write buggy code that directly overrides this rule).

Using the class

Here's some sample code that shows how the class can be used.

class Native
    void F()

class Derived : public Native{};

void SomeFunc(Native){} //Function takes a Native object
void SomeOtherFunc(Native*){} //Function takes a Native*

ref class Ref
    CAutoNativePtr<Native> m_native; //Declare the smart pointer object

    Ref(Native* pN) : m_native(pN) //Constructor that takes a T*

    //Copy constructor comes into play here
    Ref(CAutoNativePtr<Native> pN) : m_native(pN)

    //Assigning from a T*
    void Change(Native* pNew)
        m_native = pNew;

    //Assigning from another smart pointer
    void Change(CAutoNativePtr<Native> pNew)
        m_native = pNew;

    void DoStuff()
        if(!m_native) // Logical NOT applied via T* cast
            m_native->F(); //-> operator at work here
            SomeFunc(*m_native); //The T* cast at work
            SomeOtherFunc(m_native); //The T* cast at work

    bool DoComparisons(CAutoNativePtr<Native> a1, 
        CAutoNativePtr<Native> a2, CAutoNativePtr<Native> a3)
        //Operators == and != applied via T* cast
        return (a1 == a2) && (a1 != a3);		

    void Close()
        m_native.Destroy(); //Free native resource

int main()
    CAutoNativePtr<Derived> d1(new Derived); 
    CAutoNativePtr<Derived> d2(new Derived);

    //Specialized constructor for derived types is called here
    CAutoNativePtr<Native> n1(d1);

    //Specialized assignment operator for derived types is called here
    n1 = d2;

    return 0;

Class Reference


CAutoNativePtr - The constructor

There are four overloads that you can use.

  • CAutoNativePtr()
  • CAutoNativePtr(T* t)
  • CAutoNativePtr(CAutoNativePtr<T>% an)
  • template<typename TDERIVED> CAutoNativePtr(CAutoNativePtr<TDERIVED>% an)

The parameter-less constructor creates a CAutoNativePtr that wraps a nullptr object of type T. The overload that takes a T* can be used to wrap an existing pointer. Then, there are two copy constructor overloads, where one of them is to copy construct from a CAutoNativePtr<T> (same type) and the other is to copy construct from a CAutoNativePtr<TDERIVED> (which wraps a derived type of T). When you copy construct a CAutoNativePtr object, the source object's T* is detached, because only one CAutoNativePtr should own a T* at any given time, else we end up with double deletion.

~CAutoNativePtr/!CAutoNativePtr - Destructor and Finalizer

  • !CAutoNativePtr()
  • ~CAutoNativePtr()

The allocated object (if any) is freed. By having the destructor invoke the finalizer, both stack semantics and non-deterministic garbage collection are supported.

Attach - To take over an existing T*

  • void Attach(T* t)

The CAutoNativePtr will take ownership of the T*, and if there's an existing T*, it will be deleted.

Detach - Release the T*

  • T* Detach()

The underlying T* is released, and it's up to the caller to free the object now.

Destroy - Delete the underlying T*

  • void Destroy()

The underlying T* is deleted. Once you make this call, the CAutoNativePtr does not own any object any more.


operator-> - Pointer to member operator

  • static T* operator->(CAutoNativePtr<T>% an)

This returns the underlying T* object and allows the user to access T methods and fields by using the -> operator.

operator T* - Cast to T*

  • static operator T*(CAutoNativePtr<T>% an)

This is a cast to the underlying T*. This means you can pass a CAutoNativePtr object where a T* is expected, which is pretty convenient.

operator= - Assignment operator

There are three overloads for the assignment operator.

  • CAutoNativePtr<T>% operator=(T* t)
  • CAutoNativePtr<T>% operator=(CAutoNativePtr<T>% an)
  • template<typename TDERIVED> CAutoNativePtr<T>% operator=(CAutoNativePtr<TDERIVED>% an)

The first one takes a T*. If the CAutoNativePtr currently owns a T*, that's released before ownership of the new T* is taken. The other two overloads are for assignment from CAutoNativePtr objects, where one of them is specialized to handle a CAutoNativePtr object that owns a T derived object. When ownership is taken, it's transferred, which means the source objects loses ownership of the T*, and this is done to avoid double-deletion.


  • January 19th, 2006 : Article and code first published


This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


About the Author

Nish Nishant

United States United States
Nish is a real nice guy who has been writing code since 1990 when he first got his hands on an 8088 with 640 KB RAM. Originally from sunny Trivandrum in India, he has been living in various places over the past few years and often thinks it’s time he settled down somewhere.
Nish has been a Microsoft Visual C++ MVP since October, 2002 - awfully nice of Microsoft, he thinks. He maintains an MVP tips and tricks web site - where you can find a consolidated list of his articles, writings and ideas on VC++, MFC, .NET and C++/CLI. Oh, and you might want to check out his blog on C++/CLI, MFC, .NET and a lot of other stuff -
Nish loves reading Science Fiction, P G Wodehouse and Agatha Christie, and also fancies himself to be a decent writer of sorts. He has authored a romantic comedy Summer Love and Some more Cricket as well as a programming book – Extending MFC applications with the .NET Framework.
Nish's latest book C++/CLI in Action published by Manning Publications is now available for purchase. You can read more about the book on his blog.
Despite his wife's attempts to get him into cooking, his best effort so far has been a badly done omelette. Some day, he hopes to be a good cook, and to cook a tasty dinner for his wife.

Comments and Discussions

Generalmissing namespace Pinmemberhofingerandi13-May-11 1:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150326.1 | Last Updated 20 Jan 2006
Article Copyright 2006 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid