You are not logged in.
Pages: 1
Hello!
I have a class with private constructor and destructor. In one method from this class I create instance of it using std::auto_ptr to avoid memory leaks. However std::Ptr cannot access my class destructor because it's private...
I thought, that I can make specialized std::auto_ptr template friend of my class, something like this:
class A
{
friend class std::auto_ptr <A>;
};
But this doesn't compile :( How to implement this properly (if it's possible) ?
I'm still learning how to use templates in C++
Offline
Hi
What erros do you get?
The code below compiles and works ok.
#include <memory>
#include <iostream>
class A
{
public:
friend class std::auto_ptr<A>;
static std::auto_ptr<A> Create()
{
return std::auto_ptr<A>(new A);
}
private:
A(){std::cout << "A ctor" << std::endl;}
~A(){std::cout << "A destrucor" << std::endl;}
};
int main()
{
std::auto_ptr<A> ptr = A::Create();
return 0;
}
Offline
I found bug, I included "memory.h" instead of "memory".
However I found something interesting. I'm testing new C++0x features introduced in GCC 4.4 (I use v4.4.1 on my Ubuntu). This code:
class A
{
public:
friend class std::auto_ptr<A>;
static void create (); // use 'std::auto_ptr <A>' somewhere inside
private:
A ();
~A ();
};
works fine with auto_ptr, but when I replace auto_ptr with unique_ptr (recommended by C++0x) GCC fails to compile code and returns:
error: ‘virtual A::~A()’ is private
/usr/include/c++/4.4/bits/unique_ptr.h:64: error: within this context
What do you think about this error? I think it's GCC/libstdc++ bug...
Offline
Pages: 1