wolfgang
wolfgang

Reputation: 69

C++: references and smart pointers - is there such a thing as a smart reference?

Initially references have been introduced to C++ to hide the ugly pointer syntax much like many modern program languages do.

Now, with smart pointers it looks to me like we have to (again) explicitly use ptr->element or *ptr.element instead of just reference.element.

Is this the price we have to pay for having explicit control over ownership, i.e. being able to either keep it or move it on?

Or do I miss something...?

Upvotes: 0

Views: 285

Answers (1)

gerum
gerum

Reputation: 1144

Smart pointer are one of the few cases where it makes sense that there is something like ->, because there are two different member that you can access with it. Look at this example:

shared_pointer<string> a(new string);
cout << a->size() << a.use_count << endl;

There are member functions of a shared_pointer, which is useful for managing it and you can access the members of the managed object. It would be a mess if it would use the same syntax and it could create name clashes.

Upvotes: 1

Related Questions