Is it legal to use placement new on initialised memory?

后端 未结 3 2060
独厮守ぢ
独厮守ぢ 2020-12-11 02:59

I am exploring the possibility of implementing true (partially) immutable data structures in C++. As C++ does not seem to distinguish between a variable and the object that

3条回答
  •  有刺的猬
    2020-12-11 03:30

    You've actually asked 3 different questions :)

    1. The contract of immutability

    It's just that - a contract, not a language construct.

    In Java for instance, instances of String class are immutable. But that means that all methods of the class have been designed to return new instances of class rather than modifying the instance.

    So if you would like to make Java's String into a mutable object, you couldn't, without having access to its source code.

    Same applies to classes written in C++, or any other language. You have an option to create a wrapper (or use a Proxy pattern), but that's it.

    2. Using placement constructor and allocating into an initialized are off memory.

    That's actually what they were created to do in the first place. The most common use case for the placement constructor are memory pools - you preallocate a large memory buffer, and then you allocate your stuff into it.

    So yes - it is legal, and nobody won't mind.

    3. Overwriting class instance's contents using a placement allocator.

    Don't do that.

    There's a special construct that handles this type of operation, and it's called a copy constructor.

提交回复
热议问题