Does a new place set the memory numbering?

I have the following code:

struct foo {};
void bar(foo *d) {
  new(d) foo(*d);
}

Does the expression the new(d) foo(*d)object it points to remain unchanged d? More specifically, this is higher, if the class fooand all the objects contained in it recursively have only trivial copy constructors, then new(d) foo(*d)leave it *dunchanged? A situation in which this is not the case, maybe, newfirst zeroes out the memory before calling the copy constructor. Are there such sentences in C ++?

Change . There are non-trivial reasons why someone wants to do this. Consider copying objects through address spaces, say, from CPU memory to GPU memory. One solution to this is to execute an object byte byte. This works in many cases. If the class has virtual methods, then the byte copy copies the vtable pointer, which then points to some CPU memory. You can use the specified expression new(d) foo(*d)for an object to force the compiler to reset the vtable pointer.

+3
source share
5 answers

, , , , , , , .

, , undefined. d , . , , undefined, . (.. foo), undefined.

+2

, undefined: , , , - . this d, ( ), .

, , , ~foo() , undefined.

+1

, . , new , , . : new .

: - .

gcc 4.9, gcc 5.3, clang 3.4, clang 3.8 Apple clang , , . , memset. , , , .

Dignus Systems/++ z/OS , -, , ( ).

: Placement new , , .

:

#include <new>
#include <cstdint>
#include <stdio.h>

struct Test {
    char b[4];

    void show(char const* prefix) {
        for (unsigned i = 0; i < sizeof(b); ++i)
            printf("%s index %d: %d\n", prefix, i, b[i]);
    }
};

int main()
{
    char* p = new char[sizeof(Test)];

    for (unsigned i = 0; i < sizeof(Test); ++i)
        p[i] = 'Q';

    Test* t1 = new(p) Test();
    Test t2;

    t1->show("t1");
    t2.show("t2");
}

(clang 3.4 FreeBSD):

t1 index 0: 0
t1 index 1: 0
t1 index 2: 0
t1 index 3: 0
t2 index 0: 51
t2 index 1: -1
t2 index 2: 3
t2 index 3: 1
+1

Placing a new task - launching the constructor in memory, which was allocated for an object that has not yet been initialized. It does nothing and is nothing other than what you would get if you manually called the constructor (although this was not possible).

0
source

Note that you invoke the copy constructor of the object with itself as a copy. I would expect it to be just nuts. Who knows. I do not see anything in the standard that would make me expect anything.

0
source

Source: https://habr.com/ru/post/1696234/


All Articles