TransWikia.com

Trying to get an int by wraping it into void* and again wrap it back into Integer but i am not successfull

Stack Overflow Asked by Umar Farooq on November 22, 2021

#include <iostream>

class Singleton {
    static Singleton instance;
    int num;
    Singleton() = default;

    Singleton(Singleton &) = delete;
    Singleton(Singleton &&) = delete;
    Singleton &operator=(Singleton &) = delete;

public:
    static Singleton &GetInstance() {
        return instance;
    }
    void* get(){
        return (void*)num;
    }
    void setNum(const int num){
        this->num = num;
    }
};

Singleton Singleton::instance;

int main() {
    Singleton::GetInstance().setNum(12);
    std::cout << *(static_cast<int*>(Singleton::GetInstance().get())) << std::endl;
}

So my area of intrest lies in this function

void* get(){
        return (void*)num;
}

and recieving it inside int main

std::cout << *(static_cast<int*>(Singleton::GetInstance().get())) << std::endl;

But my output is not clear i think it is some udefine behaviour but my goal is to print 12 that is passed already . Help from anybody would be appreciated with proper refrence.

One Answer

If you need to return an integer value as a generic pointer (void*) then you should really do the conversion in two steps: First to an integer type that is large enough to hold both an integer and a pointer, then in the second step to the generic pointer:

void* get()
{
    return reinterpret_cast<void*>(static_cast<std::intptr_t>(num));
}

Then when you use the returned pointer, you have to remember that it's really not a pointer you returned, but the actual integer value itself. That means you need to do the opposite conversion when using the value, and not attempt to dereference it in any way:

auto value_ptr = Singleton::GetInstance().get();
std::cout << static_cast<int>(reinterpret_cast<std::intptr_t>(value_ptr)) << 'n';

I really don't recommend using values as pointers in this way generally. There are a few places where it might be needed, but this doesn't seem to be one of those.


Another possible solution is to actually return a pointer to the variable num:

void* get()
{
    return &num;
}

As this is actually a pointer, you should dereference it to get the value it points to:

auto value_ptr = Singleton::GetInstance().get();
std::cout << *static_cast<int*>(value_ptr) << 'n';

Answered by Some programmer dude on November 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP