retain-ptr icon indicating copy to clipboard operation
retain-ptr copied to clipboard

Trying to put together minimal C++ usage example

Open nordlow opened this issue 5 years ago • 3 comments

Is

#include <iostream>

using std::cout;
using std::endl;

class S
{
public:
    S(int x_) : x(x_) {}
    ~S()
    {
        cout << __PRETTY_FUNCTION__ << ":" << endl;
    }
public:
    int x;
    mutable unsigned int _rc = 1;
};

struct S_traits final
{
    static void increment (S* x) noexcept
    {
        cout << __PRETTY_FUNCTION__ << ":" << endl;
        x->_rc += 1;
    }
    static void decrement (S* x) noexcept
    {
        x->_rc -= 1;
        cout << __PRETTY_FUNCTION__ << ": rc=" << x->_rc << endl;
        if (x->_rc == 0) { delete x; }
    }
};

#include "sg14/memory.hpp"
using SP = sg14::retain_ptr<S, S_traits>;

int main(__attribute__((unused)) int argc,
         __attribute__((unused)) const char * argv[],
         __attribute__((unused)) const char * envp[])
{
    cout << "sizeof(S): " << sizeof(S) << endl;
    cout << "sizeof(SP): " << sizeof(SP) << endl;
    {
        auto rp = SP(new S(42));
    }
    return 0;
}

which prints

sizeof(S): 8
sizeof(SP): 8
static void S_traits::decrement(S*): rc=0
S::~S():

a correct usage?

nordlow avatar Nov 04 '18 20:11 nordlow

Hi, currently on the road to San Diego, but wanted to quickly respond. (Oddly enough I never got notified of your changes just the original issue. Looks like you figured out some of it)

This is one of several correct usages. If you want to have automatic opt in you can inherit via CRTP from sg14::reference_count<T> (where T is your own type). This would allow you to use the default retain_traits. Additionally, you are permitted to specialize retain_traits for your own behavior.

bruxisma avatar Nov 05 '18 02:11 bruxisma

I added some examples in #6

Flamefire avatar Nov 19 '18 09:11 Flamefire

If anyone has any objections to me closing this issue, I'll leave it open until those objections are resolved. Otherwise I'll be closing this sometime 48 hours-ish from now.

bruxisma avatar Nov 19 '18 14:11 bruxisma