reference semantic for pimpl class
I have a basic class with a pimpl, with agressive instantiation:
Code:
class MyClassImpl;
class MyClass
{
public:
MyClass() : pImpl(new MyClassImpl) {}
~MyClass(){delete pImpl;}
private:
MyClass(const MyClass&) = delete;
MyClass& operator=(const MyClass&) = delete;
MyClassImpl* pImpl;
};
Classic/Standard. However, I do hate having to use pointer semantics for all of my operations. So I thought: If I never ever manipulate the actual pointer itself, why not just keep a reference?
Code:
class MyClassImpl;
class MyClass
{
public:
MyClass() : impl(*new MyClassImpl) {}
~MyClass(){delete &impl;}
private:
MyClassImpl& impl;
};
Everything seems legit to me...
The only downside that I see, is that I can't swap or move, but this particular object is not meant to be swapped or moved.
Did I miss anything here, or can I go ahead and do this.
Re: reference semantic for pimpl class
You wouldn't be able to store it in a container either.
Re: reference semantic for pimpl class
BTW, probably it was just for brevity, but the code snippet is wrong because you're new-ing an incomplete type ( this is an error ) and you're deleting an incomplete type ( this is UB, in general ).
as far as the reference is concerned, the only problem I see is in the event of "new" returning 0; anyway, nothing really serious ... :)
Re: reference semantic for pimpl class
Quote:
Originally Posted by superbonzo
as far as the reference is concerned, the only problem I see is in the event of "new" returning 0; anyway, nothing really serious ...
Doesn't sound like a problem though since nothrow new was not used.
Re: reference semantic for pimpl class
Quote:
Originally Posted by
superbonzo
BTW, probably it was just for brevity, but the code snippet is wrong because you're new-ing an incomplete type ( this is an error ) and you're deleting an incomplete type ( this is UB, in general ).
Yeah, you caught that. It was for brevity. The code is actually in a cpp.
Quote:
Originally Posted by
superbonzo
as far as the reference is concerned, the only problem I see is in the event of "new" returning 0; anyway, nothing really serious ... :)
Quote:
Originally Posted by
laserlight
Doesn't sound like a problem though since nothrow new was not used.
Yup.
Thanks for your feedbacks.