|
|
Регистрация Восстановить пароль |
Повторная активизация e-mail |
Регистрация | Задать вопрос |
Заплачу за решение |
Новые сообщения |
Сообщения за день |
Расширенный поиск |
Правила |
Всё прочитано |
|
Опции темы | Поиск в этой теме |
02.05.2014, 15:48 | #1 |
Новичок
Джуниор
Регистрация: 02.05.2014
Сообщений: 1
|
задача по C++
Вот текст задачи:
struct A { ~A() { std::cout << "~A()"; } }; struct B : A { ~B() { std::cout << "~B()"; } }; struct C : B { ~C() { std::cout << "~C()"; } }; int main() { std::shared_ptr<A> p(false ? new B() : new C()); return 0; } //// Авторы утверждают, что правильный ответ "~B()~A()" и приводят следующее объяснение: "Пояснение: Во первых, тип тернарного выражения приводится к базовому, в данном случае, к B. Во вторых, шаред_птр сохраняет "deleter" для правильного удаления обьекта и по этой причине виртуальный деструктор для него не обязателен." В связи с чем у меня вопрос: 1) Где конкретно в стандарте написано, что в операторе ?: оба тернарных выражения должны быть приведены к одному типу? 2) Где конкретно в стандарте написано, что shared_ptr запоминает какого класса объект, чтоб вызвать соответствующий деструктор? |
02.05.2014, 16:09 | #2 |
Старожил
Регистрация: 16.12.2011
Сообщений: 2,329
|
|
02.05.2014, 16:32 | #3 |
Старожил
Регистрация: 16.12.2011
Сообщений: 2,329
|
5.16 Conditional operator [expr.cond]
conditional-expression: logical-or-expression logical-or-expression ? expression : assignment-expression 1 Conditional expressions group right-to-left. The first expression is contextually converted to bool (Clause 4). It is evaluated and if it is true, the result of the conditional expression is the value of the second expression, otherwise that of the third expression. Only one of the second and third expressions is evaluated. Every value computation and side effect associated with the first expression is sequenced before every value computation and side effect associated with the second or third expression. 2 If either the second or the third operand has type void, then the lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are performed on the second and third operands, and one of the following shall hold: — The second or the third operand (but not both) is a throw-expression (15.1); the result is of the type of the other and is a prvalue. — Both the second and the third operands have type void; the result is of type void and is a prvalue. [ Note: This includes the case where both operands are throw-expressions. — end note ] 3 Otherwise, if the second and third operand have different types and either has (possibly cv-qualified) class type, or if both are glvalues of the same value category and the same type except for cv-qualification, an attempt is made to convert each of those operands to the type of the other. The process for determining whether an operand expression E1 of type T1 can be converted to match an operand expression E2 of type T2 is defined as follows: — If E2 is an lvalue: E1 can be converted to match E2 if E1 can be implicitly converted (Clause 4) to the type “lvalue reference to T2”, subject to the constraint that in the conversion the reference must bind directly (8.5.3) to an lvalue. — If E2 is an xvalue: E1 can be converted to match E2 if E1 can be implicitly converted to the type “rvalue reference to T2”, subject to the constraint that the reference must bind directly. — If E2 is an rvalue or if neither of the conversions above can be done and at least one of the operands has (possibly cv-qualified) class type: — if E1 and E2 have class type, and the underlying class types are the same or one is a base class of the other: E1 can be converted to match E2 if the class of T2 is the same type as, or a base class of, the class of T1, and the cv-qualification of T2 is the same cv-qualification as, or a greater cv-qualification than, the cv-qualification of T1. If the conversion is applied, E1 is changed to a prvalue of type T2 by copy-initializing a temporary of type T2 from E1 and using that temporary as the converted operand. — Otherwise (i.e., if E1 or E2 has a nonclass type, or if they both have class types but the underlying classes are not either the same or one a base class of the other): E1 can be converted to match E2 if E1 can be implicitly converted to the type that expression E2 would have if E2 were converted to a prvalue (or the type it has, if E2 is a prvalue). Using this process, it is determined whether the second operand can be converted to match the third operand, and whether the third operand can be converted to match the second operand. If both can be converted, or one can be converted but the conversion is ambiguous, the program is ill-formed. If neither can be converted, the operands are left unchanged and further checking is performed as described below. If exactly one conversion is possible, that conversion is applied to the chosen operand and the converted operand is used in place of the original operand for the remainder of this section. |
02.05.2014, 16:33 | #4 |
Старожил
Регистрация: 16.12.2011
Сообщений: 2,329
|
4 If the second and third operands are glvalues of the same value category and have the same type, the result
is of that type and value category and it is a bit-field if the second or the third operand is a bit-field, or if both are bit-fields. 5 Otherwise, the result is a prvalue. If the second and third operands do not have the same type, and either has (possibly cv-qualified) class type, overload resolution is used to determine the conversions (if any) to be applied to the operands (13.3.1.2, 13.6). If the overload resolution fails, the program is ill-formed. Otherwise, the conversions thus determined are applied, and the converted operands are used in place of the original operands for the remainder of this section. 5 Otherwise, the result is a prvalue. If the second and third operands do not have the same type, and either has (possibly cv-qualified) class type, overload resolution is used to determine the conversions (if any) to be applied to the operands (13.3.1.2, 13.6). If the overload resolution fails, the program is ill-formed. Otherwise, the conversions thus determined are applied, and the converted operands are used in place of the original operands for the remainder of this section. |
02.05.2014, 16:33 | #5 |
Старожил
Регистрация: 16.12.2011
Сообщений: 2,329
|
там ещё километр текста.
я задолбался выкавыривать из пдф таки вы как нить сами. Ну или просто доверяйте информации с сайта http://en.cppreference.com/w/cpp/language Если посмотреть что пишут в стандарте, и что пишут на этом сайте - это один и тот же текст получается. Только подача материала на сайте гораздо более наглядная и читабельная. Последний раз редактировалось _Bers; 02.05.2014 в 17:16. |
Опции темы | Поиск в этой теме |
Похожие темы | ||||
Тема | Автор | Раздел | Ответов | Последнее сообщение |
Задача по подсчёту статистики использования букв. Другая задача - по длинной арифметике Pascal ABC | kimberly | Паскаль, Turbo Pascal, PascalABC.NET | 3 | 24.12.2012 17:03 |
задача на структуру(struct)/задача на работу с файлом | SevenArth | Помощь студентам | 0 | 26.04.2012 19:06 |
Задача на оптимальный расчет маршрута (задача в презентации) в табличном процессоре Excel | Toofed | Помощь студентам | 0 | 30.11.2011 01:12 |
Задача минимизации дисбаланса на линии сборки (задача минимакса) | LenZab | Microsoft Office Excel | 13 | 13.03.2011 22:51 |