4
#include <iostream>
#include <vector>
using namespace std;


class Foo
{
};
template <typename T>
class SecretPointer
{
    T* m_pointer;
public:
    SecretPointer(T* obj) : m_pointer(obj)
    {
    }
    T* getPtr() const
    {
        return m_pointer;
    }
    void setPointerBit(const bool value)
    {
        if(value)
            m_pointer = (T*)((int)m_pointer | value);
        else
            m_pointer = (T*)((int)m_pointer & ~1);
    }
    bool getPointerBit()
    {
        return ((int)m_pointer & 1);
    }
};


int main()
{
    std::vector<SecretPointer<Foo>> arr;

    SecretPointer<Foo> ptr = new Foo();
    ptr.setPointerBit(true);
    bool isT = ptr.getPointerBit();



    arr.push_back(new Foo());
    arr.push_back(new Foo());
    arr.push_back(new Foo());
    arr.push_back(ptr);
    arr.push_back(new Foo());


    for(auto& it : arr)
    {
        cout << "Secret values: " << it.getPointerBit() << " sizeof : " << sizeof(it) << endl;
    }

}

I just find for myself that every pointer has not significant bit. I read that this technology used in red-black trees algorithms.

What about sphere of application of this trick?

Where can I use with with confidence that all is fine?

user16217248
  • 3,119
  • 19
  • 19
  • 37
rikimaru2013
  • 401
  • 4
  • 13

1 Answers1

1

You must be sure that your allocations are all evenly aligned (at least, see Is there any guarantee of alignment of address return by C++'s new operation? for more information about this point).

I already did something like this using the 3 last bits as my allocator aligned on 8 bytes boundary at that time.

You type seems not to be correctly defined, I would like to see methodsfor

  1. raw values, ctor and getRaw (may be useless)
  2. bit values, getBit, setBit (last bit management)
  3. pointer value, getPtr, setPtr (all but last bit management)

You only provided a method to get the raw value...

Community
  • 1
  • 1
Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69
  • you mean about x16 machine where pointers 16 bits? Or that SecretPointer position in struct should have difference aligned ? – rikimaru2013 Dec 01 '15 at 16:30
  • 1
    No I mean that if your allocator always returns you addresses aligned to even adresses, then you can use the last bit for any purpose, but you need to manage all of this, when you need the pointer clear the last bit of the value returned, etc. – Jean-Baptiste Yunès Dec 01 '15 at 16:32