C++1y: Move & Copy Destructors

published at 01.04.2013 02:30 by Jens Weller
Save to Instapaper Pocket

A special april fools blog entry about a new idea for C++. While reading a lot of proposals, I did not have the time to prepare a proposal for Bristol about this, but probably will do so for the C++ Committee Meeting in Fall at Chicago.

As you might know, not all memory is equal, and especially destroying objects in it can be quite a performance bottleneck. As for now, we have in C++ stack and heap memory, where allocating/deallocating on the stack is much cheaper, then doing the same thing on the heap. With new proposals for transactional memory, GPU or shared memory even more expensive types of memory come sooner or later to C++. While those have their clear advantages, freeing this memory is often expensive. The perfect use case for move or copy destructors!

The syntax is straight forward:

class foo
{
//members...
public:
    foo(){}
    foo(const foo& copy)=default; // copy constructor
    foo(const foo&& move)=default; // move constructor
    ~foo(){}// destructor
    ~foo(const foo& copy) // copy destructor
    ~foo(const foo&& move) // move destructor
};

Of course it is better if we move a class for destruction rather then copying it, but in some cases you can't do that, for example if the move constructor is not provided. A lot of legacy code from the pre C++11 era will have this. So the copy destructor is needed for those cases. The principle is quite easy: move or copy the object to a more performant memory part before destroying it. The syntax is the same as with constructors, so that the compiler vendors should not have to much work implementing this.

But, how do I call it? Good Question! This should be done by a new version of delete, called placement delete:

foo* f = make_shared_memory(foo);
delete(std::memory::stack) f;

This places f in shared memory. But deleting it on the stack would be much cheaper! This can now be done with in-place delete. As deletion qualifiers I propose:

This should be extendable for further use of course. Move- and Copydestructors are a serious improvement for performance in C++1y. And with placement delete it would be easy and trivial to use this new feature.

Join the Meeting C++ patreon community!
This and other posts on Meeting C++ are enabled by my supporters on patreon!