|
| |||
|
|
Наткнулся на неизвестную мне особенность С++. В следующем фрагменте конструирование объекта X выполняется посредством вызова конструктора X(const Y&), а вот так же практически выглядещее присваивание в следующей строчке - посредством уже слайсинга, т.е. отрезания от объекта "y" его базовой части и последующего её присваивания.
class X;
class Y;
class X
{
public:
X() {}
X(const Y&);
};
class Y : public X
{
public:
Y() {}
};
void test00()
{
Y y;
X x=y; // 1 - constructor X(const Y&) called
x=y; //2 - slicing !
}UPD: в это тяжело поверить, но при компиляции выражения X x=y; компилятор не требует наличия публичного конструктора копирования Х. Меж тем, к примеру, если ввести конструктор X::X(int) и написать X x1=1; то наличие публичного конструктора копирования требуется, т.е. предыдущее формально переводится приблизительно как X x1 = X(1); хотя вызов конструктора копирования в таком контексте убирается любым компилятором, но требуется во всяком случае его доступность. А вот исходная строчка переводится как X x(y); Если таков стандарт, то я в шоке. --------------------------- Upd2: действительно, оказалось, что поведение стандартное и сложнее, чем я полагал. В частности, я считал, вслед за книгой ARM, что семантика выражения с так называемой "copy-initialization" A a=b; предполагает вызов конструктора копирования (даже если он потом убирается оптимизатором), это почти всегда так, но не всегда. ---------------------------------------- § 8.5 202 (c) ISO/IEC N3242=11-0012 ---------------------------------------- — If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. The applicable constructors are enumerated (13.3.1.3), and the best one is chosen through overload resolution (13.3). The constructor so selected is called to initialize the object, with the initializer expression(s) as its argument(s). If no constructor applies, or the overload resolution is ambiguous, the initialization is ill-formed. — Otherwise (i.e., for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3). If the conversion cannot be done or is ambiguous, the initialization is ill-formed. The function selected is called with the initializer expression as its argument; if the function is a constructor, the call initializes a temporary of the cv-unqualified version of the destination type. The temporary is a prvalue. The result of the call (which is the temporary for the constructor case) is then used to direct-initialize, according to the rules above, the object that is the destination of the copy-initialization. In certain cases, an implementation is permitted to eliminate the copying inherent in this direct-initialization by constructing the intermediate result directly into the object being initialized; see 12.2, 12.8. |
||||||||||||||