Should C++ have better pointers?

  • (2 Pages)
  • +
  • 1
  • 2

21 Replies - 3406 Views - Last Post: 20 May 2014 - 08:50 AM

#1 infernorthor  Icon User is offline

  • D.I.C Addict

Reputation: 187
  • View blog
  • Posts: 876
  • Joined: 07-February 14

Should C++ have better pointers?

Posted 10 April 2014 - 07:07 PM

I didn't think this question belonged into the help forum, sorry if this is the wrong place.

I know very well how pointers are problematic. And maybe the design choices were too limited by C.

Since C++ have strong type matching, I was thinking what if pointers were initialized as either single or moveable(default). I don't know what keyword would be suitable.
Having a pointer be single would mean it's address couldn't be incremented or have an offset but it could be reassigned.

Now I don't think this would work on single objects though.
I've thought that a pointer to object to member like ptr->member; is handled as offset so the single pointer idea couldn't work.
Maybe if you a single double pointer to the object were really a pointer accessing the members.

The purpose would maybe help also distinguishing where to use delete or delete[] perhaps.
Could this be implemented while still keeping C compatible, though C++ has moved beyond always compatible.

This post has been edited by infernorthor: 10 April 2014 - 07:10 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Should C++ have better pointers?

#2 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3469
  • View blog
  • Posts: 10,691
  • Joined: 05-May 12

Re: Should C++ have better pointers?

Posted 12 April 2014 - 08:55 PM

Why not roll your own modeled after the STL smart pointers:

template <class T>
class Single
{
public:
    Single() : _ptr(new T), _owned(true) {}
    Single(T * ptr) : _ptr(ptr), _owned(false) {}
    ~Single() { Release(); }
    Single<T>& operator=(T * ptr) { Release(); _ptr = ptr; }
    Single<T>& operator=(const Single<T>& single) { ... }
    T& operator->() { ... }

private:
    bool _owned;
    T * _ptr;

    void Release()
    {
        if (_owned)
            delete _ptr;
        _owned = false;
    }

    // declared private to prevent usage

    // no array subcription
    T& operator[](std::size_t index) {}
    const T& operator[](std::size_t index) const {}

    // no pre and post increment
    Single<T>& operator++() {}
    Single<T> operator++(int) {}

    // no pre and post decrement
    Single<T>& operator--() {}
    Single<T> operator--(int) {}

    : // other operators now allowed like addition and subtraction
};


Was This Post Helpful? 2
  • +
  • -

#3 infernorthor  Icon User is offline

  • D.I.C Addict

Reputation: 187
  • View blog
  • Posts: 876
  • Joined: 07-February 14

Re: Should C++ have better pointers?

Posted 14 April 2014 - 11:13 AM

To be honest, I haven't spent much time with the new pointers. And don't overload operators much. But, that will work great, just need get all operators working. Thanks
Was This Post Helpful? 0
  • +
  • -

#4 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1138
  • View blog
  • Posts: 7,108
  • Joined: 07-September 06

Re: Should C++ have better pointers?

Posted 14 April 2014 - 11:39 AM

C++ struggles with memory management in a lot of cases. Well, I should clarify, _it_ doesn't struggle with memory management, it simply hands all of that off to the programmer.

I think it would be nice if you were able to define a "scope" for variables and when they leave the "scope" have the option for them to be freed. For instance, I create a new Person and I hand it to a different function/ object. It would be nice to have the option to say that that function is responsible for the memory, and that function to free the Person on exit.

In general though, I am not complaining about having to pay attention to my memory. I much prefer it over, say, Java where I'm not allowed to see my pointers.
Was This Post Helpful? 0
  • +
  • -

#5 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5780
  • View blog
  • Posts: 12,594
  • Joined: 16-October 07

Re: Should C++ have better pointers?

Posted 14 April 2014 - 12:06 PM

Yes.

Which, of course, is why you have so many languages that aren't C++, but are kind of, sort of, like C++, that hide pointers.

Pointers are actually just fine. They can be hidden away in nice wrapper classes, if you must. Unless, of course, you're trying to do OO polymorphism. I would say, C++ needs better polymorphism. But, again, that's a different language.
Was This Post Helpful? 1
  • +
  • -

#6 infernorthor  Icon User is offline

  • D.I.C Addict

Reputation: 187
  • View blog
  • Posts: 876
  • Joined: 07-February 14

Re: Should C++ have better pointers?

Posted 14 April 2014 - 01:45 PM

@betawar the scoping is an interesting idea. I'm sure how that could be implemented. unscoped keyword to free it for the function it is in, though you could have problem with it if wasn't a passed pointer. So maybe have some system for compile warnings.

maybe in the same lines of class declaration you have scope declaration?



@baagavi I don't many languages. Though languages like Java really hides pointers, and C# I'm less familiar with, still has pointers, but has garbage collectors. But, I have doubt of garbage collecting especially if you are rapidly destroying and created objects. I never made something that massive, like you making particle simulation something or another.
Were there others that you thinking about?

This post has been edited by infernorthor: 14 April 2014 - 01:48 PM

Was This Post Helpful? 0
  • +
  • -

#7 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1138
  • View blog
  • Posts: 7,108
  • Joined: 07-September 06

Re: Should C++ have better pointers?

Posted 14 April 2014 - 02:28 PM

Yeah, maybe something like a "relinquish" keyword that you can give when calling function (like so):
#include <string>
#include <iostream>
using namespace std;

class Person
{
public:
  Person(std::string firstname, std::string lastname, unsigned int age);
  ~Person(void)
  // ...
  std::string name(void) const;
  unsigned int age(void) const;
private:
  std::string fname;
  std::string lname;
  unsigned int myAge;
};

void printItAll(Person* person)
{
  cout << person->name() << " is " << person->age() << " years old." << endl;
}

int main(void)
{
  Person* me = new Person("Beta", "War", 42);
  printItAll(relinquish me);
  return 0;
}

//... implementations



Where the "relinquish" would tell the compiler to free the memory at the end of the function being called, printItAll in this case). Then the compiler could throw show an error if relinquish is used with a non-pointer type along the lines of Cannot relinquish non-pointer type "int" line # file.cpp.

Overall, I think that would be interesting. Now obviously, there could be problems if you attempt to relinquish variables on the stack, or something like that, but it shouldn't be any different than attempting something like so:
int main(void)
{
  int myInt = 42;
  delete (&myInt);
  return 0;
}



At least that is my thoughts on the subject for the little bit I have been thinking about it :)
Was This Post Helpful? 0
  • +
  • -

#8 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3469
  • View blog
  • Posts: 10,691
  • Joined: 05-May 12

Re: Should C++ have better pointers?

Posted 14 April 2014 - 02:41 PM

The current C++ std::shared_ptr and std::unique_ptr seem to have the semantics that you are looking for.
Was This Post Helpful? 0
  • +
  • -

#9 BetaWar  Icon User is offline

  • #include "soul.h"
  • member icon

Reputation: 1138
  • View blog
  • Posts: 7,108
  • Joined: 07-September 06

Re: Should C++ have better pointers?

Posted 14 April 2014 - 02:48 PM

Hm, interesting. I'll have to play around with those, but perhaps you know off hand, are you allowed to do something like so:
#include <iostream>
#include <memory>
using namespace std;

void print(std::unique_ptr<int*> value)
{
  cout << value << endl;
}

int main(void)
{
  std::shared_ptr<int*> val = new int(42);
  print(val);
  return 0;
}



Or does that cause problems such as double-freeing val or not being able to switch between unique and shared pointers?
Was This Post Helpful? 0
  • +
  • -

#10 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 3469
  • View blog
  • Posts: 10,691
  • Joined: 05-May 12

Re: Should C++ have better pointers?

Posted 14 April 2014 - 08:48 PM

Sorry, I don't know. I've only always used one or the other, but not mixed and matched them like that. Whenever I used the unique_ptr<> as a function parameter type, to me that was passing on ownership to the function.

Also, you don't need the '*' within the angle brackets.

Since this is turning out to be very C++ focused, I'm moving this to the "Advanced C++" forum.
Was This Post Helpful? 0
  • +
  • -

#11 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5780
  • View blog
  • Posts: 12,594
  • Joined: 16-October 07

Re: Should C++ have better pointers?

Posted 15 April 2014 - 04:59 AM

View Postinfernorthor, on 14 April 2014 - 03:45 PM, said:

C# I'm less familiar with, still has pointers, but has garbage collectors.


C# basically started out as Java, Microsoft edition. It has pointers, but only really for interop. Using pointers makes the code "unsafe" and should be avoided if at all possible.

It's actually a curiosity of C / C++ programmers, that they often fear or mistrust GC. As pointed out, tools like std::shared_ptr have been around for a long time. Scott Meyers has a lot to say about them in Effective C++ and elsewhere.

While looking for a reference, I found this article about memory management that seems almost apropos. If nothing else, I found it interesting.

If you'd asked me about C++ a decade ago, I'd have told you it's a kitchen sink language. Today, it's probably the rest of the kitchen, too. I do not doubt there are a number of completely safe memory management paradigms that may be adopted in C++; half of which I do not know. Unfortunately, hidden within that always seems to be danger lurking for the unaware or inexperienced, waiting to blow of a limb.
Was This Post Helpful? 0
  • +
  • -

#12 NickDMax  Icon User is offline

  • Can grep dead trees!
  • member icon

Reputation: 2250
  • View blog
  • Posts: 9,245
  • Joined: 18-February 07

Re: Should C++ have better pointers?

Posted 15 April 2014 - 11:55 AM

Quote

Having a pointer be single would mean it's address couldn't be incremented or have an offset but it could be reassigned.


So you can do:

single int* sptr = &someInt;
sptr++; //illegal
sptr[4]; //illegal
sptr+10; //illegal
sptr = &newAddress; //legal


or maybe you mean "a re-assignable reference"? since a reference basically covers the first three criteria BUT it not re-assignable.
Was This Post Helpful? 0
  • +
  • -

#13 infernorthor  Icon User is offline

  • D.I.C Addict

Reputation: 187
  • View blog
  • Posts: 876
  • Joined: 07-February 14

Re: Should C++ have better pointers?

Posted 15 April 2014 - 12:38 PM

Perhaps. That would hold similar ideas. But, pointers can be zero, you can reassign a pointer with a pointer, I don't know of deleting references.

Skydiver class could encapsulate a lot of what I was saying. But, can't see why if it was useful couldn't be part of the language. I still have to look at C++11 they did add a lot of qualifiers to encapsulated pointer types.

Though I'm not sure if this the best idea to make pointers safer. I don't have particular example , I'm think more generally of better paradigms.

int * single ptr = &someInt;
int * single ptr = new int ; //ok
int * single ptr = new int[];//error 

delete[] ptr ; //error
delete ptr; //ok

void Double( int * single ptr){
    *ptr *= 2; // ok
    ptr[5] = 6;// error
}


And of course if you reassign it to the middle of an array, deleting would be bad.
So, the ownership concept would seem necessary.

Referencing were certainly a new model for some saver memory though. A reference know there is given memory.
Was This Post Helpful? 0
  • +
  • -

#14 Blindman67  Icon User is online

  • D.I.C Regular
  • member icon

Reputation: 118
  • View blog
  • Posts: 488
  • Joined: 15-March 14

Re: Should C++ have better pointers?

Posted 20 April 2014 - 07:01 AM

Why would you want fixed pointer. I cant see the point. If you are in a large project with coders everywhere then just learn to use private to keep your classes safe from prying snippets .

Some programmers will see a public property and then think they have a clever way of accessing some data and you can no longer clean up memory when done.

In big projects it should also be made clear who owns what, and he who allocates must defalcate. Nothing worse than a memory leak and half a dozen coders all shrugging there shoulders and looking with accusation at each other.

Fixing a memory issues by overloading an increment and other pointer arithmetic is the craziest idea i have heard in a long time. That's not fixing the problem that is burying your head in the sand.

I think C++ pointers are just fine. If you are having trouble with them then use a higher level language like C# and have GC cover your memory problem. But that's not safe as well and there are plenty of ways to make most GC schemes lose track of memory allocation.

If you find that you are having problems with memory then readjust your coding proprieties and focus on cleaning up. I see way to many coders that have a "I'll deal with that later." attitude. "Its only a minor leak, I fix it when I get the logic done." In my book a memory leak no matter how insignificant is a bug and knowingly ignoring a bug in your code is the worst type of programming there is.

Pointers are great, and give languages like c and C++ their speed and flexibility. Pointers are not "unsafe" its bad coding practices and attitudes that are unsafe.
Was This Post Helpful? 0
  • +
  • -

#15 SP135  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 13-May 14

Re: Should C++ have better pointers?

Posted 13 May 2014 - 03:33 AM

No, C++ definetely does not need "better pointers". C/C++ pointers give you a lot of power and that's a great thing, you just have to be very careful with them. In my code(60K LOC) there are only few usages of new and delete, so i really do not see any need for a GC language. The only thing i hate is that the "member of pointer" operator is different than "member of object" operator. Using '->' instead '.' has no advantages really.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2