Skip to content
This repository has been archived by the owner on Jan 6, 2022. It is now read-only.
This repository has been archived by the owner on Jan 6, 2022. It is now read-only.

Trying to put together minimal C++ usage example #4

Open
nordlow opened this issue Nov 4, 2018 · 3 comments
Open

Trying to put together minimal C++ usage example #4

nordlow opened this issue Nov 4, 2018 · 3 comments

Comments

@nordlow
Copy link

nordlow commented Nov 4, 2018

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 nordlow changed the title Plain C++ usage example Cannot put together minimal C++ usage example Nov 4, 2018
@nordlow nordlow changed the title Cannot put together minimal C++ usage example Trying to put together minimal C++ usage example Nov 4, 2018
@bruxisma
Copy link
Owner

bruxisma commented Nov 5, 2018

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.

@Flamefire
Copy link
Contributor

I added some examples in #6

@bruxisma
Copy link
Owner

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants