C++ primer上練習13.13自己寫程式來理解建構式、拷貝構造、析構、拷貝賦值。但是寫完發現確實有問題。
1.為什么test1(b)和test1(*c)沒有任何輸出?
2.為什么把b推入容器中只有拷貝而沒有析構?然后把*c列入容器為什么拷貝析構完還有拷貝?
#include <iostream>
#include <vector>
using std::cin; using std::cout; using std::string; using std::endl; using std::vector;
struct X
{
X() { cout << "構造" << endl; }
X(const X&) { cout << "拷貝" << endl; }
X& operator=(const X& x)
{
cout << "賦值" << endl;
return *this;
}
~X() { cout << "析構" << endl; }
};
void test1(X& x) { return; }
void test2(X x) { return; }
int main()
{
X *a = new X();
X b;
delete a;
X *c = new X();
cout << "test1(b):\n";
test1(b);
cout << "\ntest1(*c):\n";
test1(*c);
cout << "\ntest2(b):\n";
test2(b);
cout << "\ntest2(*c):\n";
test2(*c);
cout << "\nvec.push_back(b):\n";
vector<X> vec;
vec.push_back(b);
cout << "\nvec.push_back(*c):\n";
vec.push_back(*c);
system("pause");
return 0;
}
uj5u.com熱心網友回復:
因為test1傳遞的是參考,不用復制uj5u.com熱心網友回復:
2、那個析構要在vec析構之前才會發生,而vec 析構實在整個main函式結束才會呼叫轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/269663.html
標籤:C++ 語言
上一篇:Cyv'y求助!!!
下一篇:C語言中什么時候用%d和%f
