Lab0- C++ Primer
💡 unique_ptr, matrix multiplication, gdb, etc.Code download
-
Follow the document steps under the project:
// 1. Create a new warehouse, bus private // 2. clone cmu db remote code to local git clone --bare https://github.com/cmu-db/bustub.git bustub-public cd bustub-public // 3. mirror to the remote warehouse you just created git push --mirror git@github.com:sunshinejiali/bustub-private.git // 4. Delete the local copy of cmu db cd .. rm -rf bustub-public // 5. Pull your own remote warehouse code git clone git@github.com:sunshinejiali/bustub-private.git // 6. Add CMU DB as your second remote warehouse cd bustub-private git remote add public https://github.com/cmu-db/bustub.git // 7. Verify whether it has been added git remote -v // result: // origin git@github.com:sunshinejiali/bustub-private.git (fetch) // origin git@github.com:sunshinejiali/bustub-private.git (push) // public https://github.com/cmu-db/bustub.git (fetch) // public https://github.com/cmu-db/bustub.git (push) // 8. Extract changes in CMU DB git pull public master
-
The 2020 version is used, so you need to go back to a previously submitted version.
// Fallback the code to a certain version. The head points to the current target version and deletes all subsequent versions git reset --hard 444765a // Check to see if you are backing out to the correct version git log // (mandatory) submit changes git push -f
-
report errors
-
If this error is reported when installing the tool, it may be because the error is reported when running under Linux after writing the. sh file under windows.
// report errors build_support/packages.sh: line 2: $'\r': command not found build_support/packages.sh: line 13: $'\r': command not found build_support/packages.sh: line 14: syntax error near unexpected token `$'{\r'' 'uild_support/packages.sh: line 14: `main() { //solve // Open a file using vim vim packages.sh // Conversion format :set ff=unix // Save file :wq
-
make format error
// make format error /usr/bin/env: 'python': No such file or directory make[3]: *** [CMakeFiles/format.dir/build.make:57: CMakeFiles/format] Error 127 make[2]: *** [CMakeFiles/Makefile2:287: CMakeFiles/format.dir/all] Error 2 make[1]: *** [CMakeFiles/Makefile2:294: CMakeFiles/format.dir/rule] Error 2 make: *** [Makefile:214: format] Error 2 // Solution: install without python sudo apt-get install python
-
-
compile
mkdir build cd build cmake .. make // test cd .. cd build make check-tests
C + + tutorial
-
for loop
// Using references allows you to modify elements in an array. for(int& i: someDataStructure) { doSomething();} // Displays the values in the array, protects array members, enables access by value, and does not allow modification of elements. for(int i: someDataStructure) doSomething();
-
Lamba expression of Lambda function -- function with body but no name
- firstPart
- [] this means that nothing will be provided to lambda.
- [&] is used to indicate that there are some references.
- [] for copy.
- [this] is used to encapsulate classes.
- secondPart is required for the argument list of an unnamed function, but it can also be left blank.
- TypeYouReturn is used to register the type to be returned from lambda.
- BodyOfLambda is used for the operation you want to perform. Type some code that will be used to perform the operation applied in the body of this function.
- acctualParameters are used to provide input to the lambda function.
// firstPart is used for the range of variables that will be used inside the lambda function. [firstPart](secondPart) TypeYouReturn{ BodyOfLambda}(acctualParameters); // Example 1 double dUpperPart = [](double dX, double dY)double{ return dX*dX +dY*dY;} // Example 2 vectror<int> iVector; for_each( begin(iVector), end(iVector), [](int n){if(n%2==0)cout<<n<<end;});
- firstPart
-
Static Assertion
// Two parts: (1) expressions to be judged. (2) Does not match the displayed message. static_assert(evaluatedExpression, stringMessage); // example static_assert(sizeof(long long int)>=16;"This is unexpected");
-
Move and &&
// Implement the move constructor in the class MovableClass(MovableClass&&); // This is called when the configuration needs to be moved MovableClass&& operator=(MovableClass&&);
-
Pointer
- Replace NULL with nullptr. It's like initializing an empty zero value.
- New types of smart pointers: unique pointer, shared pointer, weak pointer.
-
unique_ptr is a new feature of C + +, which will enable you to protect the ownership of some resources stored in memory. If something has ownership, it cannot be shared, but it is movable. This means that you can transfer it to another unique pointer. unique_ The example of PTR will resolve the exception unsafe code.
unique_ptr<someType> suniquePtr(new someType(args)); ... uniquePtr.release();
-
shared_ptr, as its name implies, is suitable for situations where ownership of certain resources in shared memory is required.
shared_ptr<someType> somePtr(new someType(args));
-
weak_ptr allows you to access the contents that may exist in memory. If you have an object that occupies memory, you can grant access and delete the object. If you used it last time, you can call the necessary destructor.
weak_ptr<someType> weakPtr = somePtr;
-
-
Unified initialization and initialization list
If you want to use a constructor, you'd better replace the old style initialization () with {}.
-
initialization
// customary CSomeClass SomeObject(argument1,argument2); // New edition CSomeClass SomeObject={argument1,argument2};
-
Add element
// The original is out of date vector <int> ourVector; for(int i=0; i<5; ourVector.push_back(i++)); // New edition vector< int> ourVector={0,1,2,3,4,};
-
-
Constructors and inheritance
- Constructor, initializing nSomeValue
class CSomeClass { private: int nSomeValue=0; ... }
- Inheritance constructor
class CChild: public CParent { public: using CParent::CParent }
-
virtual function
- When there is inheritance and virtual methods need to be applied, it is enough to write virtual in front of the name. Virtual methods will be used for mining every time there are methods in low-level classes.
- If you want to prevent the method from being overwritten, add final in front of the method, and then you cannot modify the behavior of the method.
-
Multithreading
- When starting a thread, you can use: join, swap, detach, sleep, etc.
- If you protect some resources from other threads so that you can get the desired results now, you should add different types of mutexes to their libraries: mutexes, recursive mutexes, timed mutexes, and recursive timed mutexes.
-
Programming style
auto tuple = make_tuple("triangle", 't', 10, 15, 20); // Will have one element string and the other is a mapping of vectors map<string,vector<int>> aMap;
GDB tutorial
-
If you want to debug the main function.
gdb main // or gdb a.out // function run // or start // Go back and see what the problem is backtrace // Looking at the value at an address, x can be regarded as the abbreviation of examine. x 0xffbef014
- View the information after the program crashes. backtrace
-
Conditions and breakpoints
- The break point will return a number for later reference, such as deletion.
- Only in item_ to_ When remove equals 1, it is interrupted on line 52.
// Break point, on line 52. break LinkedList<int>::remove // Only in item_ to_ When remove equals 1, it is interrupted on line 52. condition 1 item_to_remove==1
-
Quit quit.
-
Enter step to continue running, and enter next to continue step by step.
-
ctrl + a can display a document. ctrl + L can restore the display without output from the output display and restore the normal display. q exit.
Experimental instruction
-
In this Project, three categories will be implemented: Matrix, RowMatrix, and RowMatrixOperations. These matrices are simple two-dimensional matrices and must support addition, Matrix multiplication and simplified general Matrix multiplication (GEMM).
-
Only one file needs to be modified: p0_starter.h can be found in Src / include / primer / P0 in the BusTub repository_ The file was found in starter. H.
-
In this header file, three classes to be implemented are defined. This Matrix abstract class defines the common functions of the derived class RowMatrix. This RowMatrixOperations course will use the RowMatrix object to implement the operations mentioned in the overview. Functions and member variables are specified in the file. The project requires to fill in the implementation of all constructors, destructors and member functions. Do not add any prototypes or member variables for additional functions. You only need to modify the defined functions we have provided.
-
Because some codes are not implemented, there is a parameter with DISABLED prefix in the test file to prohibit the use of some tests. Therefore, when we implement the functions that should be implemented, we can delete the DISABLED prefix to test the functions of the current function.
// For example // Original TEST(StarterTest, **DISABLED_**MultiplyMatricesTest) { // .... } // New TEST(StarterTest, MultiplyMatricesTest) { // .... }
-
Local test
// If you have built a build before, go directly to build make starter_test ./test/starter_test
-
Check the format before submitting the test
// Under build make format make check-lint make check-clang-tidy
-
Package submit test
- website: https://www.gradescope.com Registered 2020 Course Code: 5VX7JZ
zip project0.zip src/include/primer/p0_starter.h
Knowledge points
-
C + + dynamic memory allocation array https://blog.csdn.net/DumpDoctorWang/article/details/80902947
-
C++ unique_ptr smart pointer
- unique_ptr does not share its pointer, but can only use new to allocate memory, and because of unique_ptr cannot be copied and assigned. Direct initialization must be used for initialization.
unique_ptr<int> number(new int()); //Direct initialization // Empty ptr, use delete to release. unique_ptr<int> number; // Empty ptr, which is released using the d delector. unique_ptr<int,D> number(d); // Release the object it points to number = nullptr // Relinquish control of the object and return the saved pointer. Setting number to null will not free memory number.release() // The parameter can be null and built-in pointer. First release the object referred to by number, and then reset the value of number number.reset(...)
-
It cannot be copied to another, passed to a function by value, or unique in any C + + standard library algorithm that needs to be copied_ Used in PTR. There can only be one unique at a time_ PTR points to a specific object. When unique_ When PTR is destroyed, the object it points to will also be destroyed. Therefore, multiple unique are not allowed_ PTR points to the same object.
-
Only move unique_ptr. This means that ownership of memory resources will be transferred to another unique_ptr, and original unique_ptr no longer owns this resource. Move is defined in < utility >.
-
unique_ptr is defined in the header of the < memory > C + + standard library. Its efficiency is exactly the same as the original pointer and can be used in C + + standard library containers. Adding instances to the C + + standard library container is very efficient because the mobile constructor does not require unique_ptr unique_ptr copy operation.
-
Cannot copy unique_ There is an exception to the rule of PTR: we can copy or assign a unique to be destroyed_ PTR (C++ Primer 5th p418), which can return a unique value from the function_ ptr.
std::unique_ptr<RowMatrix<T>> matrix(new RowMatrix<T>(matA->GetRows(), matB->GetColumns())); // Therefore, there is no problem in writing here. matrix = MultiplyMatrices(std::move(matA), std::move(matB)); if (matrix != nullptr) { return AddMatrices(std::move(matrix), std::move(matC)); }
-
Pass unique_ptr parameters can use references to avoid ownership transfer or temporarily transfer ownership.
-
Use unique_ When PTR manages classes that are not new objects and have no destructors, it is necessary to send a message to unique_ptr passes a delegator. The difference is, unique_ The PTR manager must be unique in angle brackets_ PTR points to the type that provides the delegator after the type. Create or reset a unique_ptr object, you must provide a callable object of the same type (delegator), which accepts a T * parameter.
-
When calling number.release(), the memory referred to by number will not be released. At this time, the return value is the unique index of this memory. If the return value is not used to release or save memory, this memory will be leaked.
Coding
-
initialization:
- Use new to initialize linear, data_.
- Use memset to clear the newly created array.
- Create a unique that points to the matrix_ ptr .
std::unique_ptr<RowMatrix<T>> matrix(new RowMatrix<T>(row, col);
-
unique_ptr movement:
MultiplyMatrices(std::move(matA), std::move(matB));
-
result:
reference material
- unique_ The use and pitfalls of PTR https://blog.csdn.net/qq_33266987/article/details/78784286
- How to create and use unique_ptr instance https://docs.microsoft.com/zh-cn/cpp/cpp/how-to-create-and-use-unique-ptr-instances?view=msvc-160
- Missing reference. Please contact.