Я написал следующую программу, чтобы проверить, когда вызывается конструктор копирования и когда оператор присваивания называется:Конструкторы копирования и присваивания Операторы
#include
class Test
{
public:
Test() :
iItem (0)
{
std::cout << "This is the default ctor" << std::endl;
}
Test (const Test& t) :
iItem (t.iItem)
{
std::cout << "This is the copy ctor" << std::endl;
}
~Test()
{
std::cout << "This is the dtor" << std::endl;
}
const Test& operator=(const Test& t)
{
iItem = t.iItem;
std::cout << "This is the assignment operator" << std::endl;
return *this;
}
private:
int iItem;
};
int main()
{
{
Test t1;
Test t2 = t1;
}
{
Test t1;
Test t2 (t1);
}
{
Test t1;
Test t2;
t2 = t1;
}
}
Это приводит следующий вывод (только что добавили Empy линии, чтобы сделать его более понятным):
[email protected]:~$ ./test This is the default ctor This is the copy ctor This is the dtor This is the dtor This is the default ctor This is the copy ctor This is the dtor This is the dtor This is the default ctor This is the default ctor This is the assignment operator This is the dtor This is the dtor
второй и третий набор, ведут себя, как ожидалось, но в первом наборе копия строител ctor вызывается, даже если используется оператор присваивания.
Является ли это поведение части C++ стандарт или просто умные оптимизации компилятора (я использую GCC 4.4.1)