Using arbitrary owning pointer without templating - c++

I would like to pass (shared) ownership of an object to a function foo::bar.
The thing is I do not care, whether the ownership is exclusive or shared.
I see class foo as an interface where I do not want to care about the ownership details.
All I care about is that I can secure the lifetime of the passed smart pointer beyond the return of foo::bar.
Now I could write
class foo {
void bar( std::shared_ptr<blub> );
void bar( std::unique_ptr<blub> );
};
but this is unelegant in times where we have accumulated several smart pointer variants.
And writing an overload for every variant is quite cumbersome, especially if I want to use this scheme multiple times in my code.
Now I also do not want foo to be templated, for the obvious template complexities.
The simplest I can come up with would be a smart pointer wrapper
template <typename T>
class owning_ptr {
// Sorts out the largest type so we can allocate enough space
typedef largest<std::shared_ptr<T>, std::unique_ptr<T>, myptr<T>>::type big_type;
typedef std::aligned_storage <sizeof(big_type), std::alignment_of<big_type>::value>::type buffer_type;
buffer_type _internal;
int _type;
};
which is a bit inefficient. Is there a better way to construct the wrapper?
In the end I would really like to have the signature:
class foo {
void bar( owning_ptr<blub> );
};

Note: There's an interesting EDIT at the bottom
If you don't want to parameterize or overload on the owning pointer type, you're probably best off taking a shared_ptr<> and forcing a conversion for unique_ptr<>. Any non-template solution I can think of would have at least the same amount of overhead as a shared_ptr, most requiring a polymorphic call, a free-store allocation, or both.
You might be able to automate the conversion from shared_ptr by taking some type of proxy converter, which should allow you to take either a unique_ptr R-value or a shared_ptr without a cast or explicit conversion (other than move()) and extract a usable shared_ptr to store in your instance. Here's an example:
#include <iostream>
#include <memory>
#include <utility>
using namespace std;
// Take an instance of gimme_owned_ptr<T> to save off a shared_ptr<T>
// from either a shared_ptr or unique_ptr.
template<typename T>
struct gimme_owned_ptr {
// Make the two constructors templates so we can accept
// any convertible owning pointer:
template<typename S>
gimme_owned_ptr( unique_ptr<S> p )
: p_( shared_ptr<S>( move(p) ) )
{ }
template<typename S>
gimme_owned_ptr( shared_ptr<S> p )
: p_( p )
{ }
shared_ptr<T> get() const {
return p_;
}
private:
shared_ptr<T> p_;
};
struct Foo {
void operator()() const { v_call(); }
virtual ~Foo() { }
private:
virtual void v_call() const = 0;
};
struct Bar {
Bar( gimme_owned_ptr<Foo const> const &gop )
: foo_( gop.get() )
{ }
void operator()() const { (*foo_)(); }
private:
shared_ptr<Foo const> foo_;
};
struct Baz : Foo {
private:
virtual void v_call() const { cout << "Baz()()\n"; }
};
int main() {
unique_ptr<Baz> upf( new Baz() );
shared_ptr<Baz> spf( new Baz() );
Bar upb( move( upf ) );
Bar spb( spf );
upb();
spb();
}
Yes, this solution does use templates, but only for the gimme_owned_ptr utility class template, and only for re-use and conversion. Your own class (Bar in this case) wouldn't need to be a template, nor would you need to re-implement gimme_owned_ptr to use it with another type.
======== EDIT ========
I just checked, and the built-in conversion from unique_ptr to shared_ptr essentially does everything the gimme_owned_ptr class I wrote above. If the class takes a type of shared_ptr<T>, passing a move(unique_ptr<S>) will result in a workable conversion. So, all you really need is to take a shared_ptr and the only thing the user should have to do is call move() on unique_ptrs (which they should be doing anyway). The only reason to use something like gimme_owned_ptr would be to accept a different mixture of pointers or accept them in a different way. (For example, you could make the move() unnecessary by taking a unique_ptr<S>& and calling move() internally, but this is probably a bad idea as it will silently seize ownership.)

Related

Is there a way to prevent assignment of pointers?

A tricky question. If would like to write a function that returns a pointer to some IFoo object, is it possible to prevent the assignment of this pointer?
I do not want to make IFoo a singleton and I can hide or delete the copy and assignment operators, but does C++ actually allow a pattern, where I explicitly have to call somebody else to obtain an object?
The background question is: I am thinking about some sort of dependency container, where you should always ask the container to get some IFoo * (pointer for the sake of polymorphism). The user should never be able to save it to some local variable or member to avoid a stalled reference to it. (For scenarios where the container is instructed to return no longer Foo, which is derived from IFoo but Bar)
Edit for clarification, although user R Sahu already said that is not possible.
Indeed the example of Mark B was a perfect illustration of what I wanted to prevent:
IFoo* foo_ptr_I_will_keep_forever = obj->getIFoo();
When I wouldn't have interfaces but only explicit instance of types I could return a reference, which given a private operator= and copy ctor would suffice.
Your title says:
Is there a way to prevent assignment of pointers?
No, you can't prevent that if your function returns a pointer.
However, if you return a handle, which can be a pointer to a type that is only forward declared or an integral value that can be used to come up the real object, and make sure that all the real functionality works with the handle, then you can have more freedom over when you can delete the real object without the risk of leaving the client code with a dangling pointer.
Here's a simple program that demonstrates the concept.
#include <iostream>
#include <set>
// Foo.h
struct Foo;
using FooHandle = Foo*;
FooHandle createFoo();
void fooFunction1(FooHandle h);
void fooFunction2(FooHandle h);
// Test Program
int main()
{
FooHandle h = createFoo();
fooFunction1(h);
fooFunction2(h);
fooFunction1(h);
return 0;
}
// Foo implementation.
namespace FooImpl
{
std::set<Foo*>& getLiveFooObjects()
{
static std::set<Foo*> liveObjects;
return liveObjects;
}
bool isValid(Foo* h)
{
return (getLiveFooObjects().find(h) != getLiveFooObjects().end());
}
}
using namespace FooImpl;
struct Foo {};
FooHandle createFoo()
{
FooHandle h = new Foo{};
getLiveFooObjects().insert(h);
return h;
}
void fooFunction1(FooHandle h)
{
if ( isValid(h) )
{
std::cout << "In fooFunction1.\n";
}
else
{
std::cout << "Ooops. The handle is no longer valid.\n";
}
}
void fooFunction2(FooHandle h)
{
std::cout << "In fooFunction2.\n";
delete h;
getLiveFooObjects().erase(h);
}
Output:
In fooFunction1.
In fooFunction2.
Ooops. The handle is no longer valid.
Give them back an object (that they can store if they want) that always looks up the real one via private (friend) interfaces.
For example, an IFooCaller that implements IFoo by getting the current IFoo and forwarding all calls to it.
A middle ground answer that would prevent accidentally storing a pointer to a particular implementation, but wouldn't prevent someone from doing it on purpose:
template <typename T> class service_wrapper;
class service_manager
{
template <typename T> friend class service_wrapper;
public:
template <typename T>
service_wrapper<T> get() const;
private:
template <typename T>
T* get_instance() const;
};
template <typename T>
class service_wrapper
{
friend class service_manager;
public:
T* operator->() const;
private:
service_wrapper(service_manager const & p_sm) : sm(p_sm) { }
service_manager const & sm;
};
template <typename T>
T* service_wrapper<T>::operator->() const
{
return sm.get_instance<T>();
}
Your manager only dispenses instances of service_wrapper<T>. The operator-> implementation allows invoking on the service using wrapper->method(...);, and always fetches the implementation pointer from the service manager.
This can be circumvented like:
T *ptr = sm.get<T>().operator->();
But that's not something you can accidentally do.

Deleting a Template Type

I have a generic class that looks something like this:
template <class T>
class Example
{
private:
T data;
public:
Example(): data(T())
Example(T typeData): data(typeData)
~Example()
// ...
};
I'm a bit confused about how to implement a deconstructor for something like this. Specifically, since T is of any type, it could be memory allocated on the stack (which is always the case for Example's created via the no-argument constructor) or on the heap.
For instance, if the client makes the type for T an int* and provides a pointer to dynamic memory, how do I know to call delete on data as opposed to if the client set the type to int?
The simplest answer is: don't. Don't try to second-guess the user and do something they might not expect. Adopt the same policy as standard containers do: assume T cleans up after itself correctly.
If the client code is written correctly, it will use RAII classes (such as smart pointers) for automatic and correct management of memory and other resources. If it's not, you cannot hope to fix that in your provider code.
Make your class work with std::unique_ptr and std::shared_ptr, as well as any other custom RAII class, and let your clients do the management themselves. What if they want to store non-owning pointers, after all?
You can use Template Specialization.
template <class T>
class Example
{
private:
T data;
public:
Example()
: data(T())
{}
Example(T typeData): data(typeData)
{}
};
template <class T>
class Example<T*>
{
private:
T* data;
public:
Example() : data(nullptr){}
Example(T* typeData): data(typeData) {}
~Example()
{
delete data;
}
};
int main()
{
Example<int> e;
Example<int*> e2;
return 0;
}
You could just not worry about it like the standard library does. For example, if you create a vector of pointers you are responsible for deleting them before you let the vector go out of scope. People can then decide if they even want it to be deleted at all (maybe it's temporary for sorting and something else owns the object). They can also use smart pointers so that vector will destroy the object via the destructor for the smart pointer.
In this case, less is more. You don't have to do anything complicated. You don't have to maintain multiple versions of the template. Finally, the user of your template has more control...and responsibility as well of course.
Use memory release helper template classes that can be selected by type.
You does not need to make dublicate of your class with Template Specialization.
You can write only one class.
#include <type_traits>
template<typename T> // primary template
struct Releaser
{
template<typename V>
void release( V v ) { }
};
template<> // explicit specialization for T = std::true_type
struct Releaser<std::true_type>
{
template<typename V>
void release( V v ) { delete[] v; }
};
template <class T>
class Example
{
private:
T data;
public:
Example(): data(T()) {}
Example(T typeData): data(typeData) {}
typedef typename std::is_pointer<T>::value_type isptr_type;
~Example() {
Releaser< isptr_type >::release( data );
}
};
But need to know form of new called, so use delete or delete[].
I suggest you to use std::unique_ptr for T when you need Example to hold an owning pointer. If T is a raw pointer, then it's simply not owning and should not delete it.
If you need Example to initialize the pointer, specialize it for std::unique_ptr and call std::make_unique in the default constructor.
template<typename T>
class Example<std::unique_ptr<T>> {
Example() : data{std::make_unique<T>()} {}
/* rest of the class */
};
If you do this, you should not specialize your class for T* to do a new, as you cannot initialise non-owning pointers. You should receive it in you constructor, and maybe disable the default constructor for raw pointers if you don't want it to be null.
template<typename T>
class Example<T*> {
Example() = delete;
Example(T* data_) : data{data_}
/* data is not an owning pointer. No need for a destructor */
/* rest of the class */
};
If you follow those rules, you should have no problem with memory management.

Using an abstract deleter with std::unique_ptr

I want to have a run-time interface that offers some creation methods. These methods return unique_ptr<T>, and I want to enable custom deletion by the creating class. The thing is that I definitely don't want the interface to offer these methods directly- they should only be available in the destruction of the unique_ptr<T, SomeCustomDel>. Now, I figured that I can use std::unique_ptr<T, std::function<void(T*)>>, but I'd really rather not because I simply don't need that level of abstraction and I don't want to have to pay the heap allocation.
Any suggestions?
Your specification isn't completely clear to me, but have you considered unique_ptr<T, void(*)(void*)>? This is a very flexible type with many qualities of a dynamic deleter.
If that isn't what you're looking for, you might try something along the lines of:
class impl
{
public:
virtual ~impl();
virtual void operator()(void*) = 0;
virtual void other_functionality() = 0;
};
class my_deleter
{
impl* p_;
public:
...
void operator()(void* p) {(*p_)(p);}
void other_functionality() {p_->other_functionality();}
...
};
It is difficult to know what is best in your case without more details about your requirements.
I wish there was a standard "dynamic" deleter version of std::unique_ptr. This mythical class would allow me to attach a deleter to the unique_ptr when I instantiate it, similar to std::shared_ptr.
That said if such a type existed I suspect it would essentially be implemented with std::unique_ptr<T,std::function<void(T*)>>. The very thing you wanted to avoid.
However I think you're underestimating std::function. Its implementation is optimization to avoid hitting the heap if possible. If your deleter object remains small everything will be done on the stack (I think boost::function can statically handle deleters up to 32 bytes in size).
A for the problem of a too general deleter. You have to provide the definition of the deleter. There is no way around that. However you don't have to let the user instantiate the class, which essentially forbids them from using it. To do this make the deleter's constructor(s) require a tag structure that is only defined in the implementation file.
Or possibly the simplest solution. Put the deleter in a detail namespace. The user is still free to use it, but it's obvious that they should not and can't complain when you change it, breaking their code.
I see two options.
Option 1: Use a custom deleter that contains a function pointer and optionally a raw char array to encode some state if necessary:
template<class T>
void simply_delete(T* ptr, const unsigned char*) {
delete ptr;
}
template<class T, int StateSize>
struct my_deleter {
void (*funptr)(T*,const unsigned char*);
array<unsigned char,StateSize> state;
my_deleter() : funptr(&simply_delete<T>) {}
void operator()(T* ptr) const {
funptr(ptr,StateSize>0 ? &state[0] : nullptr);
}
};
template<class T>
using upi = unique_ptr<T,my_deleter<T,sizeof(void*)>>;
Now, you can create different upi<T> objects that store different function pointers and deleter states without the need of mentioning what exactly is happening in its type. But this is almost the same as a function<> deleter which implements the "small function optimization". You can expect a decent standard library implementation to provide a very efficient function<> wrapper for small function objects (like function pointers) that don't require any heap allocations. At least I do. :)
Option 2: Simply use shared_ptr instead of unique_ptr and make use of its built-in type erasure feature with respect to deleters. This will also allow you to support Derived->Base conversions easily. For greatest control over what is allocated where you could use the std::allocate_shared function template.
This is a response to one of the answers, not to the original question. It is an answer instead of a comment simply because of formatting reasons.
I wish there was a standard "dynamic"
deleter version of std::unique_ptr.
This mythical class would allow me to
attach a deleter to the unique_ptr
when I instantiate it, similar to
std::shared_ptr.
Here is a start of an implementation of such a class. It is fairly easy to do. I've used unique_ptr only as an exception safety aid, nothing more. It is not as full-featured as you might like. These extra features are left as an exercise for the reader. :-) What is below establishes unique ownership of the pointer and storage for the custom dynamic deleter. Note that the smart pointer owns a passed-in pointer even if the constructor of the smart pointer throws (this is actually where unique_ptr is most useful in the implementation).
#include <memory>
#include <type_traits>
namespace detail
{
class impl
{
public:
virtual ~impl() {};
};
template <class T, class D>
class erase_type
: public impl
{
T* t_;
D d_;
public:
explicit erase_type(T* t)
noexcept(std::is_nothrow_default_constructible<D>::value)
: t_(t)
{}
erase_type(T* t, const D& d)
noexcept(std::is_nothrow_copy_constructible<D>::value)
: t_(t),
d_(d)
{}
erase_type(T* t, D&& d)
noexcept(std::is_nothrow_move_constructible<D>::value)
: t_(t),
d_(std::move(d))
{}
virtual ~erase_type()
{
if (t_)
d_(t_);
}
erase_type(const erase_type&) = delete;
erase_type& operator=(const erase_type&) = delete;
};
} // detail
template <class T>
class my_pointer
{
T* ptr_;
detail::impl* impl_;
public:
my_pointer() noexcept
: ptr_(nullptr),
impl_(nullptr)
{}
template <class Y>
explicit my_pointer(Y* p)
: ptr_(static_cast<T*>(p)),
impl_(nullptr)
{
std::unique_ptr<Y> hold(p);
impl_ = new detail::erase_type<Y, std::default_delete<Y>>(p);
hold.release();
}
template <class Y, class D>
explicit my_pointer(Y* p, D&& d)
: ptr_(static_cast<T*>(p)),
impl_(nullptr)
{
std::unique_ptr<Y, D&> hold(p, d);
typedef
detail::erase_type<Y, typename std::remove_reference<D>::type>
ErasedType;
impl_ = new ErasedType(p, std::forward<D>(d));
hold.release();
}
~my_pointer()
{
delete impl_;
}
my_pointer(my_pointer&& p) noexcept
: ptr_(p.ptr_),
impl_(p.impl_)
{
p.ptr_ = nullptr;
p.impl_ = nullptr;
}
my_pointer& operator=(my_pointer&& p) noexcept
{
delete impl_;
ptr_ = p.ptr_;
impl_ = p.impl_;
p.ptr_ = nullptr;
p.impl_ = nullptr;
return *this;
}
typename std::add_lvalue_reference<T>::type
operator*() const noexcept
{return *ptr_;}
T* operator->() const noexcept
{return ptr_;}
};
Note that unlike unique_ptr (and like shared_ptr), the constructors taking a pointer are not noexcept. Although that could possibly be mitigated via the use of a "small deleter" optimization. Yet another exercise left for the reader. :-)
I found this question googling my own problem; using unique_ptr with an abstract base class pointer. All the answers are great. I found #deft_code's one to be the best for my needs.
This is what I ended up doing in my case:
Suppose T is an abstract base class type. The makeT(), func creates a new instance of some derived class, and returns the T*:
std::unique_ptr<T, std::function<void(T*)>> p(makeT(), [](T* p){p.delete();});
I just wanted to share this for those who are looking for short, copy and pasteish solution.
For the untrained c++11 eyes, the [](... syntax is a lambda.
As is mentioned in the other answers, it's not a 'function pointer' in the C sense, but a callable c++ object, which is really tiny, and should have negligible overhead to carry it around.

How to hide specific type completely using typedef?

I have a quick question about encapsulating specific types with typedef. Say I have a class Foo whose constructor takes a certain value, but I want to hide the specific type using typedef:
class Foo {
public:
typedef boost::shared_ptr< std::vector<int> > value_type;
Foo(value_type val) : val_(val) {}
private:
value_type val_;
};
But in this case, the main function still has to know the type (so it's explicitly using std::vector<int>):
int main() {
Foo::value_type val(new std::vector<int>());
val->push_back(123);
Foo foo(val);
return 0;
}
How can I fix that while still avoiding a deep copy of the vector in the Foo constructor?
Various solutions:
Foo::value_type val(new Foo::value_type::element_type());
// least change from your current code, might be too verbose or too
// coupled to boost's smart pointer library, depending on your needs
Foo::value_type val(new Foo::element_type());
// add this typedef to Foo: typedef value_type::element_type element_type;
Foo::value_type val = Foo::new_value_type();
// static method in Foo, allows you to even easily change from new (as you
// encapsulate the whole smart pointer, and can specify another deleter to the
// boost::shared_ptr)
struct Foo {
static value_type new_value_type() { // function used above
return value_type(new value_type::element_type());
}
};
However, if all you want is to have a vector member in Foo initialized from outside data without copying it, instead of actually sharing through a shared_ptr, then I wouldn't use a shared_ptr at all. Take a reference in Foo's ctor and document that it changes the object.
struct Foo {
typedef std::vector<int> value_type;
explicit Foo(value_type& val) {
using std::swap;
swap(val, _val);
}
private:
value_type _val;
};
int main() {
Foo::value_type val;
val->push_back(123);
Foo foo(val);
return 0;
}
There is no deep copy in the provided example. The shared_ptr is copied, but there is only one vector created. You can confirm this by calling push_back a second time after the Foo constructor and noticing that Foo.val_ also changes.

How to design a class where the user/caller has options to provide a custom behavior using a custom class

I encounters a problem where I want to have a class in which its behavior can be customized by another class, for example, Foo's constructor accepts a parameter of some type of class:
class Bar { //The default class that define behavior
};
template <typename T = Bar>
class Foo {
public:
Foo(T* t = 0) t_(t) {
if (t_ == 0) t_ = new T();
}
~Foo() {
delete t_;
}
}
Now if someone use Foo in a client code:
Foo foo;
Everything is fine. But, if we want to supply the custom class:
class Bar1 { };
Foo<Bar1> foo(new Bar1()); // This is OK
Bar1 b;
Foo<Bar1> foo(&b); // Error, b is not dynamically allocated
Is there any design pattern I can use to prevent this kind of mistakes? Or, is there any techniques or semantics where the user of Foo class can choose/specify who owns the bar object? So for example, the above Foo destructor can be like this:
~Foo() {
if (t_ is owned by this object) delete t_;
}
Bar or Bar1 or any class passed as t in Foo(T* t) might be a big object, so if it is possible I rather not to pass it by value.
Update:
What I have in mind is for the user to be able to do something like:
Foo foo(new Bar(1, 2, etc..));
//or this:
Bar bar(1, 2, etc..);
Foo foo(bar);
But if bar is a big object (for example, contains an array), then it would be inefficient to pass bar by value. The only way is to have bar passed by reference or pointer, but I also want the user to be able to use bar with parameterized constructor, and hence my confusion began.
Regarding to the auto variable scope, it would be safe if a user do something like:
int main() {
Bar1 bar1(1,2,3);
Foo foo(&bar1);
return 0;
}
As long as Foo does not delete bar1.
You can't detect the difference between stack and heap allocation (the standard doesn't even mention a stack), but that's not the issue here.
Foo should not be deleting things that it does not own. If it wants a copy for itself then it should just make a copy:
template <class T = Bar>
class Foo
{
T t_;
public:
Foo() {}
Foo(const T& t) : t_(t) {}
};
Or if you need it to be a pointer:
template <class T = Bar>
class Foo
{
T* t_;
public:
Foo() : t_(new T()) {}
Foo(const T& t) : t_(new T(t)) {}
};
You can't just go around deleting things that people give you, and that's regardless of whether you know if it's stack or heap allocated. What if your Foo goes and deletes it but the calling code still wants to use it? Or what if that same object is passed into two of your Foo objects and they both delete it?
Your option is either to make a copy, or not delete it.
An alternative to doing the copy would be to mark whether you are using your own or someone else's:
template <class T = Bar>
class Foo
{
T* t_;
bool owned;
public:
Foo() : t_(new T()), owned(true) {}
Foo(T* t) : t_(t), owned(false) {}
~Foo() { if (owned) delete t_; }
};
In case you are wondering, t is passed by const-ref in my previous solutions, not by value, so there is no excessive expense, although there could be an expense in the copying.
Use a smart pointer and you won't have to worry about memory management. If you really have to, I guess you should have the user of your class handle the memory they pass in, your class should be only responsible for deleting the objects that it created.
You have to consider if you really need to use pointers. A simple design like this one:
template <typename T = Bar>
class Foo1 {
T t_;
public:
Foo1() {
}
Foo1(const T& t) : t_(t) {
}
};
might be all you need. There's nothing wrong with using it like this:
int main() {
Bar1 bar1(1,2,3);
Foo1 foo(bar1); // specify custom behavior
Foo1 foooo; // get default behavior
return 0;
}
If you really need pointers, Dan provided a good answer using std::auto_ptr<>. You can guarantee you always have an object created with something like:
template <typename T = Bar>
class Foo2 {
std::auto_ptr<T> t_;
public:
Foo2() : t_(std::auto_ptr<T>(new T)) { }
Foo2(std::auto_ptr<T> t) : t_(t) {
if (t_.get() == 0) t_ = std::auto_ptr<T>(new T);
}
};
Then you can call it like this:
std::auto_ptr<Bar1> s(new Bar1());
Foo2<Bar1> foo(s);
Foo2<Bar1> foooo;
As for the user passing the address of a stack object to a smart pointer, that's really the user's fault for doing something wrong. The program will crash as soon as the auto_ptr tries to delete the object.
Short answer, No.
For any arbitrary type T to be used such as Bar1 then you have to simply accept that your class's users may write code that explodes.
However if you only construct the instance of type T when you construct the class, instad of taking a pointer to an instance you could in Foo's code construct the instance of Bar1 using a Create function. But then you can't pass arguments to the constructor.
class Bar
{
public: static Bar * Create()
}
template <typename T>
class Foo
{
public: static Foo<T>* Create() { return new Foo<T>(T::Create()); }
}
I can in now way endorse this for anything but pure fun, but here is a class that tests where it was allocated:
class AllocTester {
public:
bool on_stack() {
AllocTester outer;
return on_stack_check(&outer);
}
private:
bool on_stack_check(AllocTester *outer) {
AllocTester inner;
return (outer < &inner) == (this < &inner);
}
};
This won't work with multithreading, static variables or unusual architectures. So if you try to use this for any "real" coding you will just break you application. Only look at it as curiosity, in real life the caller of your class should be responsible to handle the allocated memory correctly.
Usually if there is a function that allocates memory, there should be a corresponding function that frees it again. If the class takes ownership of the passed pointer this should be made explicitly clear. Maybe even using auto_ptr would be a good idea since it explicitly transfers ownership of the pointer to the constructor.
To clarify my comments in Poita_'s answer:
template <typename T = Bar>
class Foo {
T& t_;
std::auto_ptr<T> pT_;
public:
Foo(T& t) : t_(t) {
}
Foo(std::auto_ptr<T> pT) : pT_(pT), t_(*pT) {
}
T& getT() const {
T* pT = pT_.get();
if (pT != NULL)
return *pT;
return t_;
}
};
You can then use it as follows:
std::auto_ptr<Bar> pBar(new Bar());
Foo<Bar> foo0(pBar);
Bar& b0 = foo0.getT();
Bar b;
Foo<Bar> foo1(b);
Bar& b1 = foo1.getT();
As this code shows, you should (almost) always place the result of new into some object which manages the memory. std::auto_ptr<> will pass ownership of the pointer to Foo. Alternatively, you could pass the pointer directly in the constructor, but that makes it easier to call Foo(&bar).