64,676
社区成员
发帖
与我相关
我的任务
分享
void testSyntax4()
{
D();
printf( "separator 1\n" );
const B& ref = D();
printf( "separator 2\n" );
D();
printf( "separator 3\n" );
}
const T& ret = D();
return ret;
class B
{
public:
B() {
printf( "B ctor: %08X\n", this );
}
~B() {
printf( "B dtor: %08X\n", this );
}
void DoSomething() const {
printf( "B DoSomething: %08X\n", this );
}
};
class D : public B
{
public:
D() {
printf( "D ctor: %08X\n", this );
}
};
const B& Get()
{
return D();
}
const B* GetPoint()
{
const B* pB = new D();
return pB;
}
void testSyntax3()
{
Get().DoSomething(); // 此处避免了D的拷贝,而且析构的时候是D的析构,不用B声明virtual析构函数
GetPoint()->DoSomething(); // 如果不用智能指针包装,内存泄露,如果用智能指针,B要声明virtual析构函数
}
class B
{
public:
B();
void DoSomething(){};
~B();
}
class D : public B
{
public:
D();
}
const B& Get()
{
return D();
}
const B* GetPoint()
{
const pB* = new D();
return pB;
}
int main()
{
Get().DoSomeThing();//此处避免了D的拷贝,而且析构的时候是D的析构,不用B声明virtual析构函数
GetPoint()->DoSomeThing();//如果不用智能指针包装,内存泄露,如果用智能指针,B要声明virtual析构函数
return 1;
}
void Person::SetGender(cosnt std::string& gender)
{
m_strGender = gender;
}
const std::string& parse_gender(int eGender)
{
eGender == 1 ? "male" : "female";
}
//就可以这样使用,避免了2次拷贝
Person p;
p.SetGender(parse_gender(1));