How to use void* as a single variable holder? (Ex. void* raw=SomeClass() )

后端 未结 1 872
攒了一身酷
攒了一身酷 2021-01-27 10:43

I am trying to make void* to hold a value (to avoid default constructor calling).

I want to:-

  • copy K to void* e.g. K k1; --> void*
相关标签:
1条回答
  • 2021-01-27 11:37

    What you are trying to do doesn't make sense. A void * is used to hold an arbitrary type of pointer, not an arbitrary type of other object. If you want to use storage for an arbitrary object type, use a char[].

    Other problems with your code include that you need to ensure correct alignment of the raw storage, use reinterpret_cast to a reference rather than static_cast to a non-reference, your in-place destructor call syntax is wrong, and that you don't construct the K object in the "raw" storage. Here's a corrected version:

    #include <string>
    #include <iostream>
    
    class K{
        public: std::string yes="yes"   ;
    };
    
    int main() {
        //objective:  k1->raw->k2  , then delete "raw"
        alignas(alignof(K)) char raw[sizeof(K)];        //<--- try to avoid heap allocation
        K k1;
        new (reinterpret_cast<K *>(&raw)) K(k1);     //<--- compile now succeeds :)
        K k2= reinterpret_cast<K &>(raw);
        std::cout << k2.yes << std::endl;           //test
        reinterpret_cast<K&>(raw).K::~K();  // call destructor
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题