| [ Web Proxy ] |
| Viewing: https://cpppatterns.com | [Back] [Original] |
12345678910111213141516171819202122232425262728293031323334 | #include <memory>
class bar;
class foo
{
public:
foo(const std::shared_ptr<bar>& b)
: forward_reference{b}
{ }
private:
std::shared_ptr<bar> forward_reference;
};
class bar
{
public:
void set_back_reference(const std::weak_ptr<foo>& f)
{
this->back_reference = f;
}
void do_something()
{
std::shared_ptr<foo> shared_back_reference = this->back_reference.lock();
if (shared_back_reference) {
// Use *shared_back_reference
}
}
private:
std::weak_ptr<foo> back_reference;
}; |
Maintain a non-owning reference to a shared dynamically allocated object to break circular dependencies.
The std::weak_ptr type represents a non-owning reference to dynamically allocated object with shared ownership (std::shared_ptr). As they do not contribute to the reference count of the managed object they refer to, the object...
Copy elements from a range to another range or container.
Count the number of occurrences of a particular value in a range of elements.
Implement the assignment operator with strong exception safety.
Delegate behavior to derived classes without incurring the cost of run-time polymorphism.
Implement a lexicographic ordering over class members.
Reduce dependencies on internal class details and improve encapsulation.
Remove compilation dependencies on internal class implementations and improve compile times.
Safely and efficiently implement RAII to encapsulate the management of dynamically allocated resources.
Utilise the value semantics of existing types to avoid having to implement custom copy and move operations.
Create a copy of an object through a pointer to its base type.
Use promises to communicate values between threads.
Check if a particular key is in an associative container.
Use the erase-remove idiom to remove elements from a container.
Allow argument values to be omitted when calling a function.
Return multiple values of different types from a function.
Read a sequence of delimited values from a single line of an input stream into a standard container.
Ensure that multiple stream reads are successful before using the extracted values.
Share ownership of a dynamically allocated object with another unit of code.
Transfer unique ownership of a dynamically allocated object to another unit of code.
Avoid manual memory management to improve safety and reduce bugs and memory leaks.
Maintain a non-owning reference to a shared dynamically allocated object to break circular dependencies.
| Web Proxy Viewer | New URL | Original Page |