Use PImpl with custom stream: is my solution optimal?

http://ideone.com/RKf3uC
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>
#include <memory>

struct Other
{
	virtual void print() = 0;
	virtual ~Other() = default;
};

struct Base
{
	Base(Other *o)
	{
		o->print();
	}
	virtual ~Base() = default;
};
struct Derived : Base
{
	Derived();
	virtual ~Derived();
private:
	struct My;
	std::unique_ptr<My> my;
};

int main()
{
	Derived d;
}

struct Derived::My : Other
{
	std::string s = "It works";
	virtual void print()
	{
		std::cout << s << std::endl;
	}
};
Derived::Derived()
: my(new My)
, Base(my.get())
{
}
Derived::~Derived() = default;
Base is std::basic_*stream, Other is std::basic_streambuf. The code generates a runtime error, as I was afraid it would, because the base has to be initialized before any members of the derived class.

Here is my solution: http://ideone.com/tSVEgp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
struct Derived : Base
{
	Derived();
	virtual ~Derived();
private:
	struct My;
	std::unique_ptr<My> my;
	My *temp; //
};

//...

Derived::Derived()
: Base(temp = new My) //
, my(temp)            //
{
	temp = nullptr; //
}
This works, but would there still be any issue with this? Is there a better way? I cannot define My inline in the header. Should I just abandon the uniue_ptr altogether?
If I were to just forget about the unique_ptr altogether, would it be better or worse to use a raw pointer?
Last edited on
closed account (o1vk4iN6)
If you want to avoid the temp pointer in the class you could do something like this, tho it's not without it's limitations.

http://ideone.com/rJ9bKh
That's clever, though what imitations are you referring to?
closed account (o1vk4iN6)
Well if you don't want to reveal the pointer you'd need 2 constructors for each. One private with the pointer and another public without it. I guess it isn't that big of a deal since the public ones are basically one liners.
That's not a limitation, that's a drawback. For a second I thought this was limited in some way, but it really isn't - it just has that drawback.
Topic archived. No new replies allowed.