cpp-ru / ideas

Идеи по улучшению языка C++ для обсуждения
https://cpp-ru.github.io/proposals
Creative Commons Zero v1.0 Universal
89 stars 0 forks source link

Compound literals #496

Open NN--- opened 2 years ago

NN--- commented 2 years ago

C99 поддерживает создание временного объекта непосредственно при передаче. Было бы хорошо иметь поддержку в C++.

int *p = (int[]){2, 4}; // creates an unnamed static array of type int[2]
                        // initializes the array to the values {2, 4}
                        // creates pointer p to point at the first element of the array
const float *pc = (const float []){1e0, 1e1, 1e2}; // read-only compound literal

int main(void)
{
    int n = 2, *p = &n;
    p = (int [2]){*p}; // creates an unnamed automatic array of type int[2]
                       // initializes the first element to the value formerly held in *p
                       // initializes the second element to zero
                       // stores the address of the first element in p

    struct point {double x,y;};
    void drawline1(struct point from, struct point to);
    void drawline2(struct point *from, struct point *to);
    drawline1((struct point){.x=1, .y=1},  // creates two structs with block scope 
              (struct point){.x=3, .y=4}); // and calls drawline1, passing them by value
    drawline2(&(struct point){.x=1, .y=1},  // creates two structs with block scope 
              &(struct point){.x=3, .y=4}); // and calls drawline2, passing their addresses
}

https://en.cppreference.com/w/c/language/compound_literal

AndreyG commented 2 years ago

В С++ это не работает по 2-м причинам:

  1. Нельзя брать адрес от временного объекта.
  2. Аргументом cast-expression-а не может быть braced-init-list.

Первый пункт, мне кажется, никто исправлять не захочет, это противоречит идеологии C++. Второй пункт исправлять не нужно, у нас есть другой синтаксис для записи того же выражения -- вместо (struct point) {.x=1, .y=1} можно писать просто point {.x=1, .y=1}.

NN--- commented 2 years ago

Первый пункт не совсем верен. Мы ведь можем передать временный объект по ссылке на константу и взять адрес на объект в функции. При этом мы ещё можем поля объявить mutable и их менять.

NN--- commented 2 years ago

По второй части согласен. Сегодня нет проблем создать объект структуры с инициализацией, кроме небольшого ограничения на порядок полей ;)