fcf::NTest::SharedPtrAny&
operator=(
const fcf::NTest::SharedPtrAny& a_source)
fcf::NTest::SharedPtrAny&
operator=(
fcf::NTest::SharedPtrAny&& a_source)
Class: fcf::NTest::SharedPtrAny
Package: fcfTest
File:
test.hpp
(
link_to_the_declaration_in_the_file
,
link_to_the_implementation_in_the_file
)
Available from version: 1.1.1
Assigns one SharedPtrAny instance to another, supporting both copy and move semantics.
The operator= allows for transferring ownership or sharing access to the managed object between fcf::NTest::SharedPtrAny instances.
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
fcf::NTest::SharedPtrAny&
- 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>
FCF_TEST_DEFINE("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