На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
Модераторы: Qraizer, Hsilgos
  
> Вопрос по классам , Кто догадается? :)
    Пусть есть класс cls:
    class cls {
    public:
    cls();
    cls(cls &);
    cls & operator=(cls &);
    ~cls();
    };

    И функция:

    cls f() {
    return cls();
    }


    Если в программе поместить такой код, то что в каком порядке будет вызываться:
    cls * c = new cls(f());


    P.S. Слабо ответить не проверив? wink.gif
      Я могу ошибаться, но сделаю предположение, что сначала будет вызван конструктор по умолчанию, а после него конструктор копии.
        1. Конструктор класса cls - создаем временный объект при выходе из функции f
        2. Коструктор копий класса cls - копирование временного объекта при конструировании по new
        3. Деструктор класса cls - разрушение временного объекта, созданного в функции f

        А в чем проблема?
          Шестая стутдя вызывает только один констркутор (по умолчанию) - работает оптимизатор.
            Стандарт 12.8/15

            Whenever a temporary class object is copied using a copy constructor, and this object and the copy have the
            same cv-unqualified type, an implementation is permitted to treat the original and the copy as two different
            ways of referring to the same object and not perform a copy at all, even if the class copy constructor or
            destructor have side effects. For a function with a class return type, if the expression in the return statement
            is the name of a local object, and the cv-unqualified type of the local object is the same as the function
            return type, an implementation is permitted to omit creating the temporary object to hold the function return
            value, even if the class copy constructor or destructor has side effects. In these cases, the object is
            destroyed at the later of times when the original and the copy would have been destroyed without the opti-mization. 111)


            class Thing {
            public:
               Thing();
               ~Thing();
               Thing(const Thing&);
               Thing operator=(const Thing&);
               void fun();
            };

            Thing f() {
              Thing t;
              return t;
            }

            Thing t2 = f();


            Here t does not need to be copied when returning from f. The return value of f may be constructed
            directly into the object t2.

            111) Because only one object is destroyed instead of two, and one copy constructor is not executed, there is still one object destroyed
            for each one constructed.
            1 пользователей читают эту тему (1 гостей и 0 скрытых пользователей)
            0 пользователей:


            Рейтинг@Mail.ru
            [ Script execution time: 0,0173 ]   [ 15 queries used ]   [ Generated: 18.07.25, 01:14 GMT ]