mr-edd.co.uk :: horsing around with the C++ programming language

value_ptr

value_ptr is a so-called smart pointer. Really, it wants to be a smart reference, but you can't overload the . operator in C++, so -> had to do. Because the use of the -> operator makes it feel like you're using a pointer, it is named as such. I'm not really happy with the name. If you can think of a better one, answers on a post card please…

In short, when a value_ptr is copied, it performs a deep copy of the pointee. There are lots of existing smart pointers designed for this purpose, but I found them lacking in some respect. Most notably value_ptr has the following features:

Recent activity

Code

Clone the repository using mercurial:

> hg clone http://bitbucket.org/edd/value_ptr

Or get a zip file of the code.

Quick start

By default value_ptr will use the copy constructor of the type used for initialization:

#include <iostream>
#include <string>
#include <value_ptr.hpp>

class base
{
    public:
        base() : number(0) { }
        virtual ~base() { }
        virtual std::string name() const { return "base"; }

        unsigned number;
};

class derived : public base
{
    public:
        virtual std::string name() const { return "derived"; }
};

int main()
{
    derived d;
    value_ptr<base> p(d); // note we don't pass a pointer, here.

    // even though the type of p is value_ptr<base>, it really points to a derived
    std::cout << p->name() << '\n'; // "derived"

    value_ptr<base> p2(p);

    p2->number = 42;

    // copying a value_ptr copies the pointee via the copy constructor by default
    std::cout << p2->number << '\n'; // 42
    std::cout << p->number << '\n'; // 0
    std::cout << p2->name() << '\n'; // "derived"
}

value_ptr can also use cloning functionality from your existing hierarchies and will prevent slicing by throwing an exception or triggering an assertion (your choice).

Further reading

Comments

brian (rip-off)

[17/12/2007 at 16:45:00]

Impressive. I'll certainly consider using it next time I am programming and need something with its particular semantics.

(optional)
(optional)
(required)

Links can be added like [this one -> http://www.mr-edd.co.uk], to my homepage.
Phrases and blocks of code can be enclosed in {{{triple braces}}}.
Any HTML markup will be escaped.