Я наткнулся на проблему того, должен ли я использовать размещение в новом или перемещение назначения для этого метода издачения. Оператор, перемещать конструктор, скопировать конструктор и конструктор по умолчанию . Каждый из этих операторов/конструкторов вывод уникальной строки, чтобы показать ее, была вызвана.
Код: Выделить всё
#include
#include
#include
struct point{
int X; int Y;
point(): X(0), Y(0) {
printf("D ");
}
point(int X, int Y): X(X), Y(Y) {
printf("P ");
}
point(const point& Point): X(Point.X), Y(Point.Y) {
printf("C ");
}
point(point&& Point): X(Point.X), Y(Point.Y) {
printf("M ");
}
point& operator=(const point& Point){
X=Point.X;
Y=Point.Y;
printf("CA ");
return *this;
}
point& operator=(point&& Point){
X=Point.X;
Y=Point.Y;
printf("MA ");
return *this;
}
~point(){
printf("DS ");
}
};
Для этого класса EmplaceBackMA that calls the constructor of element then move assigns the instance of element to the front of the array
[*]Another called EmplaceBackPN that calls the destructor of the element at the front of the array then uses placement new to instantiate a new instance of element at the front of the array.
Код: Выделить всё
template
struct array {
public:
element Buffer[10];
size_t Size = 0;
public:
template
void EmplaceBackMA(ctorargs&&... Args){
Buffer[Size] = element(std::forward(Args)...);
++Size;
}
template
void EmplaceBackPN(ctorargs&&... Args){
Buffer[Size].~element();
new(Buffer + Size) element(std::forward(Args)...);
++Size;
}
};
Код: Выделить всё
int main(){
puts("Creating Particles");
array
Particles; //DDDDDDDDDD
puts("\nEmplaceBackMA");
Particles.EmplaceBackMA(4, 4); //P MA DS
puts("\nEmplaceBackPN");
Particles.EmplaceBackPN(4, 4); //DS P
puts("\nEndingProgram");
//Is Placement New Better?
}
< /code>
output: < /p>
Creating Particles
D D D D D D D D D D
EmplaceBackMA
P MA DS
EmplaceBackPN
DS P
EndingProgram
DS DS DS DS DS DS DS DS DS DS
Подробнее здесь: https://stackoverflow.com/questions/795 ... or-a-empla
Мобильная версия