Advertisement

C++ Trick, Anyone ever tried this?

Started by June 26, 2019 07:18 AM
12 comments, last by Valakor 5 years, 3 months ago
1 minute ago, Shaarigan said:

A compiler dosen't "clear" any memory except you are in debug mode on windows for example. Otherwise you have to assume that you always get uninitialized memory anyways. A placement new/new simply places the vtable pointer on top of your object and calls the constructor, anything else is up to your class.

You can do a simple test, just create a new object instance with an int property for simplicity but do not initialize that int. In debug mode on Windows Visual Studio you'll get a zero integer when inspecting the object, in release mode it can be any kind of number due to uninitialized memory

I understand how it works. It's a  question of what's sanctioned by the standard. It's not clear to me that the standard specially disallows a compiler from clearing memory during a new operation.

Also I just did the test. It was zero in release mode too, but it doesn't really matter. It's a question of when it clears it.  It might clear memory up front not at "new" time. If it's up front it doesn't matter. However if it clears it when you do a new, my program will fail.

A short C++ Fiddle displays something arround 4198400 for me using clang.

But I think I know what you mean. If you make changes to the object after newing it, I don't think this is disallowed or undefined behavior as long as you don't try to call member functions of the class you currently changed from. This will crash but calling functions or accessing members of the base class might work without any consequences except anything strange happens to the stack so it isn't possible to unwinde it properly.

Again, it is just memory at its base

Advertisement

The placement new operator is constructing an instance of the new class in-place (hence the name) - what is actually happening here is you are calling the default constructor of the new type on the existing memory. If that constructor happens to initialize / do something with its internal members then you'd be over-writing whatever was there previously.

A second problem here is that the placement-new operator just assumes that you know what you're doing and that the block of memory is correctly-sized for the type you are new'ing into it; if the new class happens to be larger or a different layout you'll definitely run into issues.

This topic is closed to new replies.

Advertisement