Topic: Both explicit and implicit single-arg ctor?


Author: Jean-Louis Leroy <jll@skynet.be>
Date: 1998/03/07
Raw View
Hello,

I think I've come across a case where it would be interesting to
overload a ctor on its 'explicit' attribute. Consider the following
bare-bone reference-counting pointer class:

struct object
    {
    object() : refs(0)
        { }

    int refs;
    };

struct ptr
    {
    ptr(object* obj) : obj(obj)
        { if (obj) ++obj->refs; }

    ~ptr()
        { if (obj && !--obj->refs) delete obj; }

    // default & copy ctors, assignment, etc, etc

    object* obj;
    };

Suppose now that we need to mix dumb and smart pointers. We can run
into subtle bugs:

    object* obj = new object;
    set<object*> dumb_set;
    dumb_set.find(obj); // fine
    set<ptr> smart_set;
    smart_set.find(obj); // set<ptr>::find(ptr(obj)); obj is delete'd
    delete obj; // double delete

We can use 'explicit' to prevent these bugs, but this introduces lots
of explicit ctor calls and suddenly the counted-ref pointer is not so
smart anymore...

If we could overload on 'explicit', we could do a runtime check:

struct ptr
    {
    explicit ptr(object* obj) : obj(obj)
        { if (obj) ++obj->refs; }

    ptr(object* obj) : obj(obj) // implicit; not C++
        { if (obj) { assert(obj->refs); ++obj->refs; } }

    // ...

    };

Perhaps we could make the pointer even smarter:

struct ptr
    {
    ptr(object* obj) : obj(obj), implicit(true)
        { }

    explicit ptr(object* obj) : obj(obj), implicit(false)
        { if (obj) ++obj->refs; }

    ~ptr()
        { if (obj && !implicit && !--obj->refs) delete obj; }

    bool implicit; // or perhaps use a bit in the pointer

    // ...
    };

..this would make the example with set<ptr> work, but may also lead to
even subtler bugs.

Anyway, I'm pretty certain that the standard doesn't allow this. Was it
considered? If yes, why was it rejected (not counting 'vasa' reasons)?

Jean-Louis Leroy
http://ourworld.compuserve.com/homepages/jl_leroy
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]