The fifth day of C + + Learning

Keywords: C++ Back-end

1, Multiple choice questions

1. Perform the following procedure

char *str;
cin >> str;
cout << str;
If you enter abcd 1234, output (D)
A. abcd         B. abcd 1234         C.1234         D. Output garbled code or error

str is a char * pointer, uninitialized, and a wild pointer. Therefore, entering coredump to this address;

2. Perform the following procedure

char a[200];
cin.getline(a, 200, ' ');
cout << a;
If you enter abcd 1234, output (A)
A. abcd       B. abcd 1234       C.1234       D. Output garbled code or error

cin.getline(char* buf, std::streamsize count,char_type delim = '\n');

BUF --- > object accepting cin input stream
Count --- > accept character book at most
Delim --- > accept stop identifier, default is' \ n '

2, Answer questions

1. Work steps of new / and delete

Work steps of new:

1. Call the standard library function named operator new to allocate enough raw untyped memory to hold the specified type of memory

An object

2. Run a constructor of this type to initialize the object

3. Returns a pointer to the newly allocated and constructed constructor object  

delete steps:

1. Call the destructor to recycle the resources applied by the data members in the object

2. Call the standard library function named operator delete to free up the memory used by the object  
 

2. Is the destruction of an object equivalent to the call of a destructor?

This sentence is true for stack objects, but for heap objects, the call of destructor is only a step in object destruction. First call the destructor of the object, and then call the operator delete function to release itself.

3. What are the conditions for creating stack objects?

1. Be able to access the constructor for initialization. 2. Be able to execute the destructor for destruction.

**4. The standard IOStream briefly describes the status of the four streams. What do ctrl+z, Ctrl + C and Ctrl + d represent in Linux**

Status of 4 streams:
1.badbit: the bad function is used for testing, which is an unrecoverable system level error
2.failbit: using the fail function to test is a recoverable error. You can use cin.clear() to reset the flow state,
Then use cin.ignore to empty the buffer
3.eofbit: test with eof function, indicating that the file pointer reaches the end of the file
4.goodbit: use the good function to test and show that the flow state is normal before the next operation

CTRL T + Z --- > suspend to suspend the process to the background
CTRL + C --- > interrupt to terminate the process
CTRL + D ----- > indicates EOF, which sends an exit signal,

5. Why is memory aligned? What are the rules for memory alignment?

Why memory alignment------ If memory alignment is not performed, secondary access may occur when accessing data

Memory alignment rules:

1. The data member is aligned with the data member of the regular structure (struct) (or union). The first data member is placed where the offset is 0. After that, the alignment of each data member is carried out according to the value specified by #pragma pack and the length of the data member itself, whichever is smaller

#pragma pack(8)
struct x
{
	char a;
	int b;
	short c;
	char d;
}MyStructX;//12
0 1 2 3 4 5 6 7
a x x x b b b b 
c c d x
 So it's 12

struct y
{
	int b;
	char a;
	char d;
	short c;
}MyStructY;//8

0 1 2 3 4 5 6 7
b b b b a d c c --->8,
    

2. The overall alignment rule of the structure (or union). After the data members complete their own alignment, the structure (or union) itself should also be aligned. The alignment will be carried out according to the smaller of the value specified in the #pragma pack and the maximum data member length of the structure (or union).

#pragma pack(8)
struct SS
{
	int a;
	char b;
	short c;
	int d;
	struct FF
	{
		int a1;
		char b1;
		short c1;
		char d1;
	}MyStructFF;
	char e;
}MyStructSS;
0  1  2  3  4  5  6  7 
a  a  a  a  b  x  c  c
d  d  d  d  a1 a1 a1 a1
b1 x  c1 c1 d1 x  x  x	//The minimum value in FF structure is int, which is memory aligned
e  x  x  x 
So it's 28

3. Structure as a member. If there are some structure members in a structure, the internal structure members shall be stored from the address of the integer multiple of the maximum element size of the member and the integer multiple of the smallest of the values specified by #pragmapack# pragma pack(n) alignment factor

struct DD
{
	int a;
	char b;
	short c;
	int d;

	struct FF
	{
		double a1;
		char b1;
		short c1;
		char d1;
	}MyStructFF;

	char e;//40

}MyStructDD;

0	1	2	3	4	5	6	7
a	a	a	a	b   x	c	c
d	d	d	d	x	x	x	x //The largest FF structure is double, and the structure is aligned
a1	a1	a1	a1	a1	a1	a1	a1
b1	x	c1	c1	d1	x	x	x	//Structure alignment, so the total number of bytes is 40

3, Programming problem

1. Implement the code that can only generate stack objects and the code that can only generate heap objects in the new/delete expression respectively

a.new/delete job test code:

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include<string>


class Student
{
public:
	Student(int id, const char *name)
		:_id(id)
		, _name(new char[strlen(name) + 1]())
	{
		cout << "Student()Constructor" << endl;
		strcpy(_name, name);
	}

	~Student()
	{
		if (_name)
		{
			
			delete[]_name;
			_name = nullptr;
		}
		cout << "~Student()Destructor" << endl;
	}

	void *operator new(size_t sz)
	{
		cout << "operator new" << endl;
		void *ret = malloc(sz);
		return ret;
	}

	void operator delete(void *pointer)
	{
		cout << "operator delete" << endl;
		free(pointer);
	}

	void print()const
	{
		cout << "id:" << _id << endl
			<< "name:" << _name << endl;
	}
private:
	int _id;
	char *_name;
};
//1. Question 1: are object destruction and destructor execution equivalent?
//--1. For objects on the stack, it is equivalent. 2. For objects on the heap, the call of the destructor is only a step of object destruction. The real destruction is in the delete of the operator
//2. Question 2: does the member functions operator new and delete have this pointer? No, operator new/delete is a global static function, which is shared by all members
//3. Question 3: what happens when the operator new/delete function is placed outside the class without the class name and scope qualifier, and how to explain it?
void test01()
{
	Student *pstu = new Student(100, "Jackie");//1. Apply for space 2. Call constructor 3. Return pointer.
	pstu->print();

	delete pstu;

	//Student St = Student(20, "Jerry");
	//St.print();
}
int main()
{

	test01();

	system("pause");
	return EXIT_SUCCESS;
}

b. Only objects can be generated in the stack: set the operator new/delete function to private

Conditions for the existence of stack objects: 1. Be able to access the constructor for initialization; 2. Be able to execute the destructor for destruction.

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include<string>

/*
When using the new expression, there are three steps:
1.Call the standard library function named operator new to allocate enough original uninitialized memory,
2.Run a constructor of the call type to initialize the object
3.Returns a pointer to the newly assigned constructor object.

Steps to use delete:
1.Call the destructor to recycle the resources applied by the data members in the object
2.Call the standard library function of operator delete to free the memory used by the object
*/
class Student
{
public:
	Student(int id, const char *name)
		:_id(id)
		, _name(new char[strlen(name) + 1]())
	{
		cout << "Student()Constructor" << endl;
		strcpy(_name, name);
	}

	void print()const
	{
		cout << "id:" << _id << endl
			<< "name:" << _name << endl;
	}


	~Student()
	{
		if (_name)
		{

			delete[]_name;
			_name = nullptr;
		}
		cout << "~Student()Destructor" << endl;
	}
private:
	int _id;
	char *_name;

	void *operator new(size_t sz)
	{
		cout << "operator new" << endl;
		void *ret = malloc(sz);
		return ret;
	}

	void operator delete(void *pointer)
	{
		cout << "operator delete" << endl;
		free(pointer);
	}


};

void test01()
{
	//Student *pstu = new Student(100, "Jackie");// 1. After the operator new / delete is set to private, access will be denied when using new, so an error will be reported
	//pstu->print();

	//pstu->destroy();

	Student St = Student(20, "Jerry");//
	St.print();
}
int main()
{

	test01();

	system("pause");
	return EXIT_SUCCESS;
}

c. Only objects can be generated in the heap:

         1. Just make the destructor private

         2. You also need the first function in the class to destroy the heap object

         3. When deleting this in a class, first call the destructor to release the members in the class, and then release itself through operator delete

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include<string>

/*
When using the new expression, there are three steps:
1.Call the standard library function named operator new to allocate enough original uninitialized memory,
2.Run a constructor of the call type to initialize the object
3.Returns a pointer to the newly assigned constructor object.

Steps to use delete:
1.Call the destructor to recycle the resources applied by the data members in the object
2.Call the standard library function of operator delete to free the memory used by the object
*/
class Student
{
public:
	Student(int id, const char *name)
		:_id(id)
		, _name(new char[strlen(name) + 1]())
	{
		cout << "Student()Constructor" << endl;
		strcpy(_name, name);
	}

	void *operator new(size_t sz)
	{
		cout << "operator new" << endl;
		void *ret = malloc(sz);
		return ret;
	}

	void operator delete(void *pointer)
	{
		cout << "operator delete" << endl;
		free(pointer);
	}

	void destroy()
	{
		if (this)
		{
			delete this;//Will run to call the destructor, release the member function first, and then run the operator delete function to release itself
			
		}
		
	}
	void print()const
	{
		cout << "id:" << _id << endl
			<< "name:" << _name << endl;
	}
private:
	int _id;
	char *_name;
	

	~Student()
	{
		if (_name)
		{

			delete[]_name;
			_name = nullptr;
		}
		cout << "~Student()Destructor" << endl;
	}

};

void test01()
{
	Student *pstu = new Student(100, "Jackie");//1. Apply for space 2. Call constructor 3. Return pointer.
	pstu->print();

	pstu->destroy();

	//Student St = Student(20, "Jerry");// If the destructor is placed under private permission, an error will be reported
	//St.print();
}
int main()
{

	test01();

	system("pause");
	return EXIT_SUCCESS;
}

4, Algorithm problem (optional, if you can't do it, you can't do it)

1. Title: enter an integer array and implement a function to adjust the order of numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the second half of the array.

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
#include<string>
class Solution
{
public:
	void odd(int *array, int len)
	{
		int k = 0;
		for (int i = 0; i < len; i++)
		{
			if (array[i] % 2 != 0)
			{
				int temp = array[i];
				array[i] = array[k];
				array[k] = temp;
				k++;
			}

		}
	}
};
int main()
{
	Solution s1;
	int array[10] = { 1,2,3,4,5,6,7,8,9,10 };

	s1.odd(array,10);

	for (int i = 0; i < 10; i++)
	{
		cout << array[i] << endl;
	}



	system("pause");
	return EXIT_SUCCESS;
}

Posted by Bricktop on Sat, 30 Oct 2021 07:15:45 -0700