current position:Home>C + + parameterless constructor (difference between stack and heap)

C + + parameterless constructor (difference between stack and heap)

2022-05-15 05:09:44Junmo vv

1. Custom type

#include <iostream>
using namespace std;
class Test
{
public:
	Test() {
		cout << "T constructor" << endl;
	}
	~Test() {
		cout << "T destructor" << endl;
	}
		
	
};

Test t2()
{
	Test *p3 = new Test;
	cout << "t2 function" << endl;
	return *p3;
}


int main()
{
	cout << "heap" << endl; // Heap objects   The nonparametric structure of   function  2 Anyone can 
	Test *p = new Test();
	delete p;
	p = nullptr;

	Test *p2 = new Test;
	delete p2;
	p2 = nullptr;

	cout << endl;
	cout << "stack" << endl;
	Test t1;
	cout << "t1 end" << endl;
	Test t2();   // At this point, the bracketed   Just made a statement    The return value of the function is a Test The object of  , The function name is t2  ps: Generally speaking, it is written to other files   Then declare here , At this time, only demo 
	t2();
	cout << "t2 end" << endl;

	return 0;
}

therefore Test t2() Will not be considered a parameterless constructor , Just function declaration , Otherwise there will be ambiguity

2. The base type

new Will only apply for space , After adding parentheses, it will be initialized to 0( Maybe some compilers It will be optimized to 0, But we still need to add it ourselves , Don't rely on the compiler )

 

copyright notice
author[Junmo vv],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/135/202205142225592913.html

Random recommended