operator=() method from fcf::NTest::SharedPtrAny class
Class:
Package: fcfTest
File: test.hpp
Available from version: 1.1.1
Assigns one
The
The implementation handles both:
- Copy Assignment: Increases the reference count of the source object.
- Move Assignment: Transfers ownership from the source to the target, leaving the source in a null state, without affecting the reference count.
Result
- A reference to the current instance (*this) to allow for assignment chaining.
Example: Copy and Move Assignment Semantics
Demonstrates how to use copy assignment to share ownership and move assignment to transfer ownership between instances.
#define FCF_TEST_IMPLEMENTATION
#include <fcfTest/test.hpp>
#include <string>
#include <iostream>
FCF_TEST_DECLARE ("SharedPtrAny", "Demo", "AssignmentTest"){
struct Data {
std::string val;
Data (std::string v) : val(v) {}
};
// 1. Initialize two pointers
fcf::NTest::SharedPtrAny ptr1 = fcf::NTest::SharedPtrAny ::make <Data >("Original");
fcf::NTest::SharedPtrAny ptr2;
// 2. Copy Assignment
// ptr2 now shares ownership with ptr1. Reference count should be 2.
ptr2 = ptr1;
FCF_TEST (ptr2.count () == 2, "Reference count should be 2 after copy");
// 3. Move Assignment
// We create a temporary pointer and move it to ptr1.
// ptr1 will now own the data, and the temporary will be null.
FCF_TEST (ptr1.count () == 2, "Count before move");
fcf::NTest::SharedPtrAny temp = fcf::NTest::SharedPtrAny ::make <Data >("Temp");
ptr1 = std::move (temp);
// After move: ptr1 owns "Temp", temp is null, ptr2 still owns "Original"
FCF_TEST (ptr1.count () == 1, "ptr1 count should be 1 after move");
FCF_TEST (!temp, "temp should be null after move");
FCF_TEST (ptr2.count () == 1, "ptr2 count should be 1");
// 4. Verify data integrity
Data * data = ptr1.cast <Data >();
FCF_TEST (data != nullptr && data->val == "Temp", "Data integrity check failed");
}
int main(int a_argc, char* a_argv[]) {
bool error = false;
fcf::NTest::cmdRun (a_argc, a_argv, fcf::NTest::CRM_RUN , &error);
return error ? 1 : 0;
}
Output:
Performing the test: "SharedPtrAny" -> "Demo" -> "AssignmentTest" ...
[SUCCESS] Test completed successfully (0.000`003`955 sec)
[SUCCESS] All tests were completed.
Tests: 1 passed, 0 failed, 0 skipped, 1 total
Duration: 0.000`003`955 sec
VPSDime is an industry leading VPS hosting company that provides virtualized server services with high performance, availability and friendly support.