On Wednesday, 21 November 2018 16:06:08 UTC+2, Jan Riewenherm wrote:
> Hi,
>
> i´ve got an issue where i do not really find a proper solution.
>
> We have locking objects that take a pointer as argument and protect simultaneous access to the same object from different threads. These locking objects have a singleton in the backed but thats not the point of interest here.
>
> What i would like to prevent is that the locking object is used in the wrong way.
>
> Code Snippped of the locking helper object.
> class LockingObject
> {
> LockingObject(void* pObjectToLock)
> {
> Singleton_Lock(pObjectToLock);
> }
That constructor leaves private member m_pObjectToLock
uninitialized.
> ~LockingObject()
> {
> Singleton_Unlock(m_pObjectToLock);
> }
That destructor passes uninitialized member.
> private:
> void* m_pObjectToLock
> }
>
> How to use the locking object:
> function test()
> {
> LockingObject object(this);
> do_something_on_this();
> }
>
> As soon as the locking object is created the simultaneous access is protected.
> As soon as i run out of the scope of my function the locking objects is freeed.
>
> The problem i have:
> function test()
> {
> LockingObject(this);
Note that the temporary constructed above must be destroyed by now.
> do_something_on_this();
> }
>
> How to prevent calling the constructor where the created object is not used at all? c++17 [[nodiscard]] does not work for Constructors.
Technically it is possible to replace that particular public
constructor with a public factory method and private
constructor. Inlining and RVO might achieve that there
are no performance differences.
The compilers do not warn there because it might be
code as its designer desired:
std::ofstream("filename"); // creates ./filename if it doesn't exist
Philosophically all useful languages have to allow endless
ways to express lies and nonsenses for to achieve that
at least some truths can be expressed in those as well.
Blocking all lies and nonsense will be achieved only when
nothing useful can be expressed anymore.
>
> The locking object is a very generic approach to lock access from different threads and leads to a very low ressource consumption as i do not need to have dedicated locking objects for members or functions i want to protect. So please do not take a closer look at how other locking mechanisms might work. I would like to focus on the problem of having constructors which do not actually create an object.
>
> Any advice appreciated.
Always try to post code that compiles, runs and demonstrates
the issue that you have. Otherwise it is hard to realize
what sort of defect or lack of expertise is its cause.