#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Example{
public:
Example():i(1){ std::cout<<"exmapl"<<std::endl;}
Example(const Example& test) { i=test.i;std::cout<<"copy exampl"<<std::endl;}
Example& operator=(const Example& test)
{
std::cout<<"= example"<<std::endl;
}
~Example()
{
std::cout<<"~ example"<<std::endl;
}
int i;
};
void foo(Example ex)
{
}
void foo2(Example& ex)
{
}
int main(){
std::cout<<"first"<<std::endl;
Example ex2;
foo(ex2);
std::cout<<"second"<<std::endl;
foo2(ex2);
std::cout<<"third"<<std::endl;
Example* ex3=new Example;
delete ex3;
std::cout<<"fourth"<<std::endl;
std::vector<Example> vec(10);
system("pause");
return 0;
}
一个变形,可以看到在一个scope退出时在栈上的对象发生了析构
#include <iostream>
#include <string>#include <vector>
using namespace std;
class Example{
public:
Example():i(1){ std::cout<<"exmapl"<<std::endl;}
Example(const Example& test) { i=test.i;std::cout<<"copy exampl"<<std::endl;}
Example& operator=(const Example& test)
{
std::cout<<"= example"<<std::endl;
}
~Example()
{
std::cout<<"~ example"<<std::endl;
}
int i;
};
void foo(Example ex)
{
}
void foo2(Example& ex)
{
}
int main(){
std::cout<<"first"<<std::endl;
Example ex2;
foo(ex2);
std::cout<<"second"<<std::endl;
foo2(ex2);
std::cout<<"third"<<std::endl;
Example* ex3=new Example;
delete ex3;
std::cout<<"fourth"<<std::endl;
{
std::vector<Example> vec(10);
}
system("pause");
return 0;
}