занятная выходит картина кстати
Код:
#include "stdafx.h"
#include <iostream>
struct A
{
A(int v):i(v){
std::cout<<__FUNCTION__<<' '<<i<<std::endl;
}
~A(){
std::cout<<__FUNCTION__<<' '<<i<<std::endl;
}
int i;
operator int() const {
return i;
}
A& operator=(const A& a)
{
std::cout<<__FUNCTION__<<std::endl;
i=a.i;
return *this;
}
};
class B
{
const A& m_a;
public:
B(const A& a): m_a(a){
}
B& operator=(const B& b){
const_cast<A&>(m_a)=b.m_a;
return *this;
}
operator int() const {
return m_a.i;
}
};
A foo(int v)
{
return A(v);
}
int _tmain(int argc, _TCHAR* argv[])
{
{
A a1(1);
A a2(2);
B b1(a1);
B b2(a2);
std::cout<<a1<<std::endl;
std::cout<<a2<<std::endl;
std::cout<<b1<<std::endl;
std::cout<<b2<<std::endl;
b1=b2;
std::cout<<a1<<std::endl;
std::cout<<a2<<std::endl;
std::cout<<b1<<std::endl;
std::cout<<b2<<std::endl;
}
{
B b3(A(3));
std::cout<<b3<<std::endl;
}
{
B b4(foo(4));
std::cout<<b4<<std::endl;
}
{
const A& a5=foo(5);
std::cout<<a5<<std::endl;
}
return 0;
}
такая картина:
Код:
A::A 1
A::A 2
1
2
1
2
A::operator =
2
2
2
2
A::~A 2
A::~A 2
A::A 3
A::~A 3
3
A::A 4
A::~A 4
4
A::A 5
5
A::~A 5
зы: за одно тут протестировал такую задачку. как-то хотел сделать в классе конст-референс поле на другой тип. и вот в оператора присваивания оказывается нельзя так просто присвоить ссылку. а const_cast<A&>(m_a)=b.m_a; ведет к присваиванию самого типа А (да и без const_cast тоже - присвоение типа. только компилировать не хочет) . тогда я плюнул и поменял на указатель.
Социальные закладки