solution to cyclic dependency in shared_ptr without using weak_ptr

Hi ppl :),

I wished to know if there is any construct provided by C++ so that we can have smart pointers behave as raw pointers with an additional capability of automatic destruction.

I understand that

1) We could use shared_ptr but it has issues of cyclic dependency.
2) unique_ptr, but then on assignment, the source pointer loses ownership.

Is there any construct that allows

3) automatic destruction like shared pointer and cyclic dependency is not there.
4) assignment works like raw pointer assignment and source ptr also has the ownership.

If there is any other best practice for replacing the raw pointer, kindly let me know. I'd be glad to know about the best practices for replacing raw pointers and avoiding memory leaks via any other language constructs or design.

Thanks :)
Last edited on
The only solution is a tracing garbage collector.
For example: https://www.hboehm.info/gc/
unique_ptr, but then on assignment, the source pointer loses ownership.

copy assignment is actually deleted for std::unique_ptr but you could use move assignment:
http://en.cppreference.com/w/cpp/memory/unique_ptr/operator%3D
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <memory>
#include <string>

struct Person{std::string m_name;
        Person(const std::string& name) : m_name(name){}
        ~Person(){std::cout << "Goodbye " << m_name << "\n";}};

int main()
{
    std::unique_ptr<Person> p = std::make_unique<Person>(std::string("John"));
  //  std::unique_ptr<Person> q = p;//error: use of deleted function
    std::unique_ptr<Person> q = std::move(p);
}


I'd be glad to know about the best practices

it's not possible to give a one-size-fits-all reply to this query, the choice of the type of pointers will depend on the nature of the program
Last edited on
kapil2905 wrote:
I'd be glad to know about the best practices for replacing raw pointers and avoiding memory leaks via any other language constructs or design.

There are design guidelines, such as

"Never transfer ownership by a raw pointer (T*)" https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-raw

"Use a unique_ptr<T> to transfer ownership where a pointer is needed" https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-unique_ptr

"Avoid new and delete outside resource management functions" (aka "no naked new"): https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-new

etc.

(and don't even bother with shared_ptr unless you have a real non-deterministic non-hierarchical shared ownership problem - if you use shared_ptr appropriately, then "cyclic dependencies" never even come up)
Last edited on
Topic archived. No new replies allowed.