Re: Is this portable? [static pointer casts, char* arithmetic]
On 14 Apr., 19:27, SG <s.gesem...@gmail.com> wrote:
On 14 Apr., 18:03, "Alf P. Steinbach" <al...@start.no> wrote:
Why a member of?
Goals:
- copy-on-write wrapper "cow<>" for value types
- supports conversions from cow<U> to cow<T> in
case Convertible<U*,T*>
- manage the life-time of only one heap allocated object
I should add that I expected such a conversion not to create a new
copy (of the "pointee") but just to "work" polymorphically (which is
probably too much to ask for).
A simple example would look like this:
void test_string()
{
cow<string> x = string("hello");
cow<string> y = x;
cout << "*x --> " << *x << endl;
cout << "*y --> " << *y << endl;
cout << "shared = " << (&*x == &*y) << endl;
x.wref() += "123"; // "wref" for write access ...
cout << "*x --> " << *x << endl;
cout << "*y --> " << *y << endl;
cout << "shared = " << (&*x == &*y) << endl;
}
which is supposed to output:
*x --> hello
*y --> hello
shared = 1
*x --> hello123
*y --> hello
shared = 0
Without the polymorphism requirement this would be fairly easy to
achieve. But I also tried to make this code:
struct base
{
private:
virtual void greet_once() const
{ cout << "hello from base\n"; }
public:
void greet() const
{ for (int k=0; k<repeat; ++k) greet_once(); }
int repeat;
};
struct derived : base
{
private:
void greet_once() const
{ cout << "hello from derived\n"; }
public:
~derived()
{ cout << "this is ~derived speaking\n"; }
};
void test_polymorphism()
{
cow<base> x = derived();
x.wref().repeat = 3;
x->greet();
}
to output the following text:
this is ~derived speaking
hello from derived
hello from derived
hello from derived
this is ~derived speaking
where the first "~derived" message is due to the temporary in the copy-
initialization and the 2nd one comes from the copy of derived hidden
behind a type-agnostic abstract wrapper.
Cheers!
SG