From the boost library documentation I read this:
Conceptually, smart pointers are seen as owning the object pointed to,
and thus responsible for deletion of the object when it is no longer
needed.
I have a very simple problem: I want to use RAII for pointer attributes of a class that is Copyable and Assignable.
The copy and assignment operations should be deep: every object should have its own copy of the actual data. Also, RTTI needs to be available for the attributes (their type may also be determined at runtime).
Should I be searching for an implementation of a Copyable smart pointer (the data are small, so I don't need Copy on Write pointers), or do I delegate the copy operation to the copy constructors of my objects as shown in this answer?
Which smart pointer do I choose for simple RAII of a class that is copyable and assignable? (I'm thinking that the unique_ptr with delegated copy/assignment operations to the class copy constructor and assignment operator would make a proper choice, but I am not sure)
Here's a pseudocode for the problem using raw pointers, it's just a problem description, not a running C++ code:
// Operation interface
class ModelOperation
{
public:
virtual void operate = ();
};
// Implementation of an operation called Special
class SpecialModelOperation
:
public ModelOperation
{
private:
// Private attributes are present here in a real implementation.
public:
// Implement operation
void operate () {};
};
// All operations conform to ModelOperation interface
// These are possible operation names:
// class MoreSpecialOperation;
// class DifferentOperation;
// Concrete model with different operations
class MyModel
{
private:
ModelOperation* firstOperation_;
ModelOperation* secondOperation_;
public:
MyModel()
:
firstOperation_(0),
secondOperation_(0)
{
// Forgetting about run-time type definition from input files here.
firstOperation_ = new MoreSpecialOperation();
secondOperation_ = new DifferentOperation();
}
void operate()
{
firstOperation_->operate();
secondOperation_->operate();
}
~MyModel()
{
delete firstOperation_;
firstOperation_ = 0;
delete secondOperation_;
secondOperation_ = 0;
}
};
int main()
{
MyModel modelOne;
// Some internal scope
{
// I want modelTwo to have its own set of copied, not referenced
// operations, and at the same time I need RAII to for the operations,
// deleting them automatically as soon as it goes out of scope.
// This saves me from writing destructors for different concrete models.
MyModel modelTwo (modelOne);
}
return 0;
}
If you accept some requirements on your types, this can be done without requiring implementing virtual clone functions for all types. The particular requirements are that the types have accessible copy constructors, which some would deem undesirable because of potential for accidental slicing. Proper use of friending may mitigate the drawbacks of that, though.
If such is acceptable one can go about this by erasing the derived types under an interface that provides copy functionality:
template <typename Base>
struct clonable {
// virtual copy
// this clone function will be generated via templates
// no boilerplate is involved
virtual std::unique_ptr<clonable<Base>> clone() const = 0;
// expose the actual data
virtual Base* get() = 0;
virtual Base const* get() const = 0;
// virtual destructor
// note that this also obviates the need for a virtual destructor on Base
// I would probably still make it virtual, though, just in case
virtual ~clonable() = default;
};
This interface is implemented by a class templated on the most derived type, and thus knows how to make normal copies through the copy constructor.
template <typename Base, typename Derived>
struct clonable_holder : clonable<Base> {
// I suppose other constructors could be provided
// like a forwarding one for emplacing, but I am going for minimal here
clonable_holder(Derived value)
: storage(std::move(value)) {}
// here we know the most derived type, so we can use the copy constructor
// without risk of slicing
std::unique_ptr<clonable<Base>> clone() const override {
return std::unique_ptr<clonable<Base>>(new clonable_holder(storage));
}
Base* get() override { return &storage; }
Base const* get() const override { return &storage; }
private:
Derived storage;
};
This will generate virtual copy functions for us without extra boilerplate. Now we can build a smart pointer-like class on top of this (not quite a smart pointer because it does not give pointer semantics, but value semantics instead).
template <typename Base>
struct polymorphic_value {
// this constructor captures the most derived type and erases it
// this is a point where slicing may still occur
// so making it explicit may be desirable
// we could force constructions through a forwarding factory class for extra safety
template <typename Derived>
polymorphic_value(Derived value)
: handle(new clonable_holder<Base, Derived>(std::move(value))) {
static_assert(std::is_base_of<Base, Derived>::value,
"value must be derived from Base");
}
// moving is free thanks to unique_ptr
polymorphic_value(polymorphic_value&&) = default;
polymorphic_value& operator=(polymorphic_value&&) = default;
// copying uses our virtual interface
polymorphic_value(polymorphic_value const& that)
: handle(that.handle->clone()) {}
polymorphic_value& operator=(polymorphic_value const& that) {
handle = that.handle->clone();
return *this;
}
// other useful constructors involve upcasting and so on
// and then useful stuff for actually using the value
Base* operator->() { return handle.get(); }
Base const* operator->() const { return handle.get(); }
// ...
private:
std::unique_ptr<clonable<Base>> handle;
};
This is just a minimal interface, but it can easily be fleshed out from here to cover more usage scenarios.
It's a bit late, but for future viewers: There's a ready-to-use implementation in my header-only library Aurora and its SmartPtr tutorial. With Aurora, it's trivial to implement deep-copy through smart pointers. The following code works for any copyable type T:
aurora::CopiedPtr<T> first(new T);
aurora::CopiedPtr<T> second = first; // deep copy
This makes it often unnecessary to implement The Big Three/Five if your classes have pointer members.
It sounds like need to be able to make a smart pointer that creates a new copy of the object each time another smart pointer object is created. (Whether that copy is "deep" or not is up to the constructor of the object, I guess; the objects you're storing could have many levels deep of ownership, for all we know, so "deep" depends on the meaning of the objects. The main thing for our purposes is that you want something that creates a distinct object when the smart pointer is constructed with a reference from another one, rather than just taking out a pointer to the existing object.)
If I've understood the question correctly, then you will require a virtual clone method. There's no other way to call the derived class's constructor correctly.
struct Clonable {
virtual ~Clonable() {}
virtual Clonable* clone() = 0;
};
struct AutoPtrClonable {
AutoPtrClonable(Clonable* cl=0) : obj(cl) { }
AutoPtrClonable(const AutoPtrClonable& apc) : obj(apc.obj->clone()) { }
~AutoPtrClonable() { delete obj; }
// operator->, operator*, etc
Clonable* obj;
};
To use sample code, make it into a template, etc.
I've never heard about ready-to-use realisation, but you can simply do it by yourself.
First of all your should write some template wrapper class which has virtual clone method, returning copy of stored object. And then write some polymophic holder of that class which would be copyable
and don't forget about checked delete
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Checked_delete
You have two solutions ( actually you have many more, but these make most sense to me :) ):
First, you can use std::unique_ptr. This is a good solution because it forces you to have one instance per pointer. (using std::shared_ptr instead would work as well, but if you do not add the code explicitely, copy and assignment for shared_ptr will "share" - especially what you want to avoid).
If you use std::unique_ptr, your copy constructor and assignment operator should explicitly deep-copy (using either a virtual clone method in the pointee's interface, or new operator in the call to the unique_ptr constructor).
Second, you can roll your own. There's nothing complicated about it, and we're talking about a small (10-20 lines or so) utility class.
Personally, if I had to use this smart pointer class in one place, I would use std::unique_ptr. Otherwise (multiple pointers, same behavior) I would roll my own, simply so I wouldn't have to repeat the deep copy for many instances (to keep with the DRY principle).
Related
I had the idea to use std::unique_ptr as a base class for another class that manages some kind of external resource.
Let's assume my program needs to manage resources provided by a C-like library via the following functions: R* lib_create_resource(A* allocator); and void lib_destroy_resource(R* resource, A* allocator);. I would like to create a class that manages this resource, so I thought that using std::unique_ptr as a base class would be a good idea. Here's a pseudo-implementation:
struct Resource: public std::unique_ptr<R, std::function<void(R*)>> {
Resource():
unique_ptr{
lib_create_resource(&my_allocator),
[this](R* r) { lib_destroy_resource(r, &my_allocator); }
}
{ }
/* Other functions that manipulate the resource */
private:
A my_allocator;
};
Why am I using std::unique_ptr as a base class rather than as a non-static member? Because I would like to expose std::unique_ptr's methods, such as get(), reset(), operator bool(), etc., and this way I don't need to manually re-define each of them, especially when the library provides many kinds of different resources instead of just one, and I want to write a separate wrapper for each of them.
Why not use std::unique_ptr<R, std::function<void(R*)>> on its own then, without the Resource class? Because I would like to extend std::unique_ptr and provide additional methods, specific to this type of resource.
Now, the above pseudo-implementation has two major problems, which are the main point of my question.
Since base classes are initialised before non-static members, my_allocator is passed to lib_create_resource() uninitialised. This isn't hard to fix, as I can just default-initialise the unique_ptr base and re-assign it in the constructor's body, but I think it's easy to forget about this.
Similarly, during destruction, the non-static members are destroyed before the base classes. First, my_allocator will be destroyed, then ~unique_ptr() will be called, which in turn will call lib_destroy_resource() with my_allocator. But at that point, my_allocator no longer exists.
I haven't been able to come up with any solution for issue number 2. Is there a way to re-design this class so that lib_destroy_resource() doesn't access my_allocator outside its lifetime?
Of course, one solution would be to manually call lib_destroy_resource() or std::unique_ptr::reset() at the appropriate times, but automatic resource management with RAII is considered good practice, especially when exceptions are involved. So is there a better way to accomplish this, possibly by implementing my own std::unique_ptr-like class?
Ignoring other problems with such inheritance, 2. is easy to fix in analogous way to how you fixed 1. Reset the base in the destructor body:
~Resource() {
reset();
}
This way the deleter is called before any member is destroyed.
Because I would like to expose std::unique_ptr's methods, such as get(), reset(), operator bool()
One thing that you could do is a stateless base, that delegates such functions through CRTP. Something like this:
template <class Derived, class Delegate>
struct Raii
{
Delegate& crtp_delegate()
{
return static_cast<Derived&>(*this).delegate();
}
constexpr typename Delegate::pointer
get() const noexcept
{
return crtp_delegate().get();
};
constexpr void
reset(typename Delegate::pointer ptr = Delegate::pointer()) noexcept
{
return crtp_delegate().reset(ptr);
};
constexpr explicit
operator bool() const noexcept
{
return static_cast<bool>(crtp_delegate());
}
};
struct Resource: public Raii<
Resource, std::unique_ptr<R, std::function<void(R*)>>> {
protected:
std::unique_ptr<R, std::function<void(R*)>>&
delegate()
{
return ptr;
}
private:
A my_allocator;
std::unique_ptr<R, std::function<void(R*)>> ptr;
};
I have a certain type called A and I want to create multiple instances of std::unique_ptr<A, void(*)(A *ptr)> without explicitly passing the custom deleter every time. This is what I came up with:
void ADeleter(A *ptr) {
// custom deletion logic
}
class APtr : public std::unique_ptr<A, void(*)(A *ptr)> {
APtr() : APtr(nullptr) {}
APtr(A *ptr) : std::unique_ptr<A, void(*)(A *ptr)>(ptr, ADeleter) {}
};
Is it safe (or even a good practice) to inherit from std::unique_ptr (or other smart pointer classes) in order to abstract construction with a custom deleter?
No, the only classes in std:: you should inherit from have virtual destructors. The design of most of std is template parameters as extension points, rather than subclassing.
What you want instead is
struct ADeleter {
void operator()(A *ptr) {
// custom deletion logic
}
};
using APtr = std::unique_ptr<A, ADeleter>;
A problem that might ( but should never ) arise is that because std::unique_ptr doesn't have a virtual destructor you shouldn't call delete on an object that has as different dynamic type than the pointer that refers to it (for example, deleting APtr through a pointer of std::unique_ptr) because that's UB which would be ironic since smart pointers are there to stop raw new and delete in the first place.
Other than that, I see no immediate issue with your way.
You should not inherit from any class if you don't know if it has virtual destructor. Of course it can be done, but you have to be careful. It happens that unique_ptr don't have virtual destructor. So I suggest insted of inheritance use composition. Eg:
template<typename T>
class Ptr {
public:
//TODO: here provide all needed member functions for Ptr class.
private:
std::unique_ptr<A, void(*)(A *ptr)> ptr;
};
Note that your question is opinion based.
If you are going to use pointer with specific deleter in many places - why not. I don't see any issues with that.
One recommendation I can give - use callable class as a deleter. Your APtr instance takes 2 pointers: one to an object, another one to a deleter function. If you use separate empty class for deleter, the result will only take 1 pointer and will be able to avoid additional function call on destruction.
You don't need to subclass, you can just use a using directive as follows:
class MyClass; //defined elsewhere
struct MyClass_deleter
{
MyClass_deleter() = default;
void operator()(MyClass* object)
{
// delete or clean up object here
}
};
using MyClass_pointer = std::unique_ptr<MyClass, MyClass_deleter>;
// and use it as follows:
MyClass_pointer p(new MyClass());
You can do something like this:
template <typename T>
using unique_ptr_with_my_deleter = std::unique_ptr<T, my_deleter>;
//[...]
unique_ptr_with_my_deleter<int> u(new int(0));
Note that you need a C++11 compliant compiler for this to work.
std::unique_ptr has a deleted copy constructor, which means that if you have a unique_ptr in your class Foo as a data member then you must write your own copy constructor for Foo and manually deep-copy that member (even if the compiler-generated copy constructor would be fine for all other members).
In order to be able to copy in a polymorphic way, the clone() method pattern can be used. Let's assume our objects have a clone method like this:
class Base {
virtual std::unique_ptr<Base> clone() = 0;
};
Foo looks like this now:
class Foo {
public:
...
Foo(Foo const& other)
: b(other.b->clone())
, // init 10 more members that could otherwise be auto-copied just fine
// with the automatically generated copy constructor
{}
...
private:
std::unique_ptr<Base> b;
//10 more data members
};
Now, I found a way to auto-clone Foo::b, by writing a wrapper over unique_ptr that defines the copy constructor and assignment by calling clone.
template <typename T>
class auto_cloned_unique_ptr
{
private:
std::unique_ptr<T> up;
public:
// copy constructor
auto_cloned_unique_ptr(auto_cloned_unique_ptr<T> const& other)
: up(other.up->clone()) {}
// copy assignment
auto_cloned_unique_ptr<T>& operator =(auto_cloned_unique_ptr<T> const& other)
{
this->up = other.up->clone();
return *this;
}
auto_cloned_unique_ptr(std::unique_ptr<T> _up)
: up(std::move(_up)) {}
// Delegate everything else to unique_ptr
auto_cloned_unique_ptr(auto_cloned_unique_ptr<T>&& other)
: up(std::move(other.up)) {}
auto_cloned_unique_ptr<T>& operator =(auto_cloned_unique_ptr<T>&& other)
{
this->up = std::move(other.up);
return *this;
}
auto operator *() const {return *up;}
auto operator->() const {return up.operator->();}
auto get() -> const {return up.get();}
};
Now if we use this we don't need to define our own copy constructor:
class Foo2 {
public:
...
private:
auto_cloned_unique_ptr<Base> b;
//10 more data members
};
Is such an approach very much frowned upon (for using a non-standard wrapper over unique_ptr)?
Let me first paraphrase what you want to do: You want that each instance of Foo has its own instance of Base in b; in particular, if you copy a Foo, the copy will have its own new Base, initially with the same "value". In other words, Base should behave like a value.
At the same time, you can't store Base directly in Foo because it is an abstract class. In other words, you want b to be polymorphic.
There you have it: you want a polymorphic value. Other people have recognized this need and proposed for C++20 as polymorphic_value<Base>. From the documentation:
The class template, polymorphic_value, confers value-like semantics on
a free-store allocated object. A polymorphic_value may hold an
object of a class publicly derived from T, and copying the
polymorphic_value will copy the object of the derived type.
It has a reference implementation that you can use as of now. Very simply put, it is an wrapper around std::unique_ptr similar to what you propose.
The problem with your approach is that it is changing the meaning of a unique_ptr. The key thing about a unique_ptr is that it tells who is the owner of an object. If you add a copy constructor for unique_ptr, what does that mean? Are you copying the ownership? A and B both uniquely own the thing? That does not make sense. If they share ownership, then you should be using the shared_ptr to indicate the shared ownership. If you want to have a unique owner of a copy of the object, you would naturally indicate that by make_unique(*pFoo). With base and derived objects, having the base object have a
virtual unique_ptr<Foo> Clone() const=0;
is a perfectly normal construct. That is, the derived classes know how to copy themselves so they don't produce a sliced copy, but they return a unique_ptr to the base class to indicate that you will own the copy they have produced. Within these clone operations, yes, you will need to explicitly handle non-copyable members of the derived classes, so you won't be able to just use a default or generated copy constructor. You need to answer "what does it mean to copy something that contains this thing that can't be copied?"
As a concrete example, what would it mean to copy a derived class that had a mutex? What if it were locked and another thread were waiting on it? See why it's hard to give a general answer?
This approach is fine, but you should be very carefull not to clone your objects when you did not intentd to.
Also inherriting from unique_ptr might improve performance
Have seen some related questions, but not this exact one...
I've treated classes as fitting into a few major categories, let's say these four for simplicity:
Value Classes which have some data and a bunch of operations. They can be copied and meaningfully compared for equality (with copies expected to be equal via ==). These pretty much always lack virtual methods.
Unique Classes whose instances have identity that you disable assignment and copying on. There's usually not an operator== on these because you compare them as pointers, not as objects. These quite often have a lot of virtual methods, as there isn't risk of object-slicing since you're being forced to pass them by pointer or reference.
Unique-but-Clonable Classes which disable copying, but are pre-designed to support cloning if that's what you really want. These have virtual methods, most importantly those following the virtual construction / cloning idiom
Container Classes which inherit the properties of whatever they're holding. These tend not to have virtual methods...see for instance "Why don't STL containers have virtual destructors?".
Regardless of holding this informal belief system, a couple times I've tried adding a virtual method to something copyable. While I may have thought it would "be really cool if that worked", inevitably it breaks.
This led me to wonder if anyone has an actual good example of a type which has virtual methods and doesn't disable copying?
The only counter-example that I have are classes that are meant to be stack-allocated and not heap-allocated. One scheme I use it for is Dependency Injection:
class LoggerInterface { public: virtual void log() = 0; };
class FileLogger final: public LoggerInterface { ... };
int main() {
FileLogger logger("log.txt");
callMethod(logger, ...);
}
The key point here is the final keyword though, it means that copying a FileLogger cannot lead to object-slicing.
However, it might just be that being final turned FileLogger into a Value class.
Note: I know, copying a logger seems weird...
There's nothing inherently wrong in being able to copy a polymorphic class. The problem is being able to copy a non-leaf class. Object slicing will get you.
A good rule of thumb to follow is never derive from a concrete class. This way, non-leaf classes are automatically non-instantiable and thus non-copyable. It won't hurt to disable assignment in them though, just to be on the safe side.
Of course nothing is wrong with copying an object via a virtual function. This kind of copying is safe.
Polymorphic classes are normally not "value-classes" but it does happen. std::stringstream comes to mind. It'not copyable, but it is movable (in C++11) and moving is no different from copying with regard to slicing.
Virtual dispatch happens a runtime. The only reason one should want it is when the actual, dynamic type of an object cannot be known until runtime. If you already knew the desired dynamic type when writing the program, you could use different, non-virtual techniques (such as templates, or non-polymorphic inheritance) to structure your code.
A good example for the need for runtime typing is parsing I/O messages, or handling events – any kind of situation where one way or another you'll either have some sort of big switch table to pick the correct concrete type, or you write your own registration-and-dispatch system, which basically reinvents polymorphism, or you just use virtual dispatch.
(Let me interject a warning: Many people misuse virtual functions to solve problems that don't need them, because they're not dynamic. Beware, and be critical of what you see.)
With this said, it's now clear that your code will be dealing mostly with the polymorphic base classes, e.g. in function interfaces or in containers. So let's rephrase the question: Should such a base class be copyable? Well, since you never have actual, most-derived base objects (i.e. the base class is essentially abstract), this isn't really an issue, and there's no need for this. You've already mentioned the "clone" idiom, which is the appropriate analogue of copying in a polymorphic.
Now, the "clone" function is necessarily implemented in every leaf class, and it necessarily requires copying of the leaf classes. So yes, every leaf class in a clonable hierarchy is a class with virtual functions and a copy constructor. And since the copy constructor of a derived class needs to copy its base subobjects, all the bases need to be copyable, too.
So, now I believe we've distilled the problem down to two possible cases: Either everything in your class hierarchy is completely uncopyable, or your hierarchy supports cloning, and thus by necessity every class in it is copyable.
So should a class with virtual functions have a copy constructor? Absolutely. (This answers your original question: when you integrate your class into a clonable, polymorphic hierarchy, you add virtual functions to it.)
Should you try to make a copy from a base reference? Probably not.
Not with a single, but with two classes:
#include <iostream>
#include <vector>
#include <stdexcept>
class Polymorph
{
protected:
class Implementation {
public:
virtual ~Implementation() {};
// Postcondition: The result is allocated with new.
// This base class throws std::logic error.
virtual Implementation* duplicate() {
throw std::logic_error("Duplication not supported.");
}
public:
virtual const char* name() = 0;
};
// Precondition: self is allocated with new.
Polymorph(Implementation* self)
: m_self(self)
{}
public:
Polymorph(const Polymorph& other)
: m_self(other.m_self->duplicate())
{}
~Polymorph() {
delete m_self;
}
Polymorph& operator = (Polymorph other) {
swap(other);
return *this;
}
void swap(Polymorph& other) {
std::swap(m_self, other.m_self);
}
const char* name() { return m_self->name(); }
private:
Implementation* m_self;
};
class A : public Polymorph
{
protected:
class Implementation : public Polymorph::Implementation
{
protected:
Implementation* duplicate() {
return new Implementation(*this);
}
public:
const char* name() { return "A"; }
};
public:
A()
: Polymorph(new Implementation())
{}
};
class B : public Polymorph {
protected:
class Implementation : public Polymorph::Implementation {
protected:
Implementation* duplicate() {
return new Implementation(*this);
}
public:
const char* name() { return "B"; }
};
public:
B()
: Polymorph(new Implementation())
{}
};
int main() {
std::vector<Polymorph> data;
data.push_back(A());
data.push_back(B());
for(auto x: data)
std::cout << x.name() << std::endl;
return 0;
}
Note: In this example the objects are copied, always (you may implement shared semantics, though)
If I want to clone a polymorphic object in C++ (i.e. an instance of a class A which is derived from some other class B), the easiest way seems to give B a virtual clone member function, that has to be overridden by A and looks like this
A* clone(){
return new A(*this);
}
My problem is, that I find this unnecessary boilerplate code, as this is almost always needed, if one wants to use run-time polymorphic features of C++. How can it be circumvented?
Thanks
Why I need this:
My use case can be abstracted to the following example:
I have a class Integral, which evaluates the integral of some function. Do do this, they have a member which is a pointer to the class MathFunction. This abstract class contains a pure virtual function evaluate which takes one argument. I I wanted to implement the power function I would create a class PowFunction : class MathFunction. This class would have a member exponent and the function evaluate would look like this:
double evaluate(x){
return pow(x,exponent);
}
As stated the member MathFunction of class Integral has to be polymorhpic, which requires it to be a pointer. To answer the questions of the commenters with another question. Why wouldn't I want to be able to make copies of MathFunction objects?
I really want the Integral to "own" its MathFunction, meaning, that it can alter the parameters (like exponent) without changing the MathFunction of any other Integral object. This means every Integral needs to have its own copy. This requires a clone() function for MathFunctions, doesn't it?
One alternative i thought of: If several Integral objects can share the same MathFunction via a pointer to the same address, I could create copies of Integral objects without the need to copy the MathFunction. But in this case I would have to make all the properties const or somehow readonly, which is not very elegant either. Also, which Integral object should handle delete the MathFunction object?
Why you need this:
Are you seriously saying, that as soon as you work with polymorphic objects you don't ever need a copy operation? What makes polymorphic object different from other objects in this respect?
Using this argumentation, you could also throw the copy constructor and copy assignment operator out of the C++ standard!
Reduce the need to clone polymorphic objects. Really, I rarely find the need for this in my own code, and the comments on the question suggest that I'm hardly alone in the opinion that if you find yourself cloning everything, you're probably designing it wrong.
Of course, never to be unhelpful, you could indeed use the Curiously Recurring Template Pattern.
template<typename T> struct Clone {
virtual T* clone() { return new T(static_cast<const T&>(*this)); }
};
I handled this issue with a macro... it's ugly, but it works to avoid inconsistencies.
/** An interface that can be inherited by any class that wants to provide a Clone()
* method that will return a copy of itself.
*/
class ICloneable
{
public:
ICloneable() {}
virtual ~ICloneable() {}
virtual ICloneable * Clone() const = 0;
};
#define DECLARE_STANDARD_CLONE_METHOD(class_name) virtual ICloneable * Clone() const {new class_name(*this);}
[...]
public MyCloneableClass : public ICloneable
{
public:
MyCloneableClass() {}
DECLARE_STANDARD_CLONE_METHOD(MyCloneableClass);
};