Heap-free pimpl. Incorrect or superstition?

前端 未结 1 2028
清酒与你
清酒与你 2021-01-11 11:44

Edit: This question dates from before C++17. These days std::launder or equivalent should be added to the line noise. I don\'t have time to update the code to match right no

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-11 11:48

    Yes, this is perfectly safe and portable code.

    However, there is no need to use placement new and explicit destruction in your assignment operators. Aside from it being exception safe and more efficient, I'd argue it's also much cleaner to just use the assignment operator of example_impl:

    //wrapping the casts
    const example_impl& castToImpl(const unsigned char* mem) { return *reinterpret_cast(mem);  }
          example_impl& castToImpl(      unsigned char* mem) { return *reinterpret_cast<      example_impl*>(mem);  }
    
    
    example& example::operator=(const example& other)
    {
        castToImpl(this->state) = castToImpl(other.state);
        return *this;
    }
    
    example& example::operator=(example&& other)
    {
        castToImpl(this->state) = std::move(castToImpl(other.state));
        return *this;
    }
    

    Personally, I also would use std::aligned_storage instead of an manually aligned char array, but I guess thats a matter of taste.

    0 讨论(0)
提交回复
热议问题