# C++ makes me cry.

This topic is 4843 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have finally sat down to do a large scale project in C++. However, I am starting to wonder how to do anything (read on). It is becoming painfully apparent that I can't use vectors on actual data; that I will need to use vectors of pointers. This is because I will be using interfaces extensively. Should I use boost's shared_ptr? What other options are there? Surely they don't manage memory all themselves? Maybe I should use C#...

##### Share on other sites
Okay.

More seriously, do you have a question? Do you have a specific problem? (No, asking about boost::shared_ptr does not meet the criteria, because Google answers those questions.)

Quote:
 Maybe I should use C#...
Maybe you should consider what your goals are first, and then choose the most appropriate tool for the course?

##### Share on other sites
Quote:
 Original post by thedevdanIt is becoming painfully apparent that I can't use vectors on actual data; that I will need to use vectors of pointers. This is because I will be using interfaces extensively. Should I use boost's shared_ptr? What other options are there? Surely they don't manage memory all themselves?

You don't really need to use boost::shared_ptr if you can organize your memory allocation/deallocation. I allocate/deallocate objects in one place, and pass constant pointers around (to prevent unintended deallocation).

##### Share on other sites
Well, you can have objects which are non-virtual interfaces, with functions which forward onto a member object which has a virtual implementation.

The Envelope Letter Idiom describes this.

class InterfaceImpl;class Interface {public:    Interface(InterfaceImpl*);    void SomeFunction();private:    InterfaceImpl* m_pImpl;};

//this is what gets derived from and overriddenclass InterfaceImpl {public:    virtual void DoSomeFunction();};

void Interface::SomeFunction() {    m_pImpl->DoSomeFunction();}

You'd probably want to use a smart pointer to hold the InterfaceImpl pointer.

edit: The overall point being that you hold containers of Interface objects, not pointers to Interface objects:

typedef std::vector<Interface> Interfaces;Interfaces i;i.push_back(Interface(new MyInterfaceImpl));i.push_back(Interface(new YourInterfaceImpl));i.push_back(Interface(new AnotherInterfaceImpl));

##### Share on other sites
Quote:
 Original post by alniteI allocate/deallocate objects in one place, and pass constant pointers around (to prevent unintended deallocation).

It's okay to delete a constant pointer.

##### Share on other sites
just use c# and your pain will stop, as simple as that!

##### Share on other sites
Quote:
 Original post by abnormaljust use c# and your pain will stop, as simple as that!

C# is not a panacea for poor software engineering.

##### Share on other sites
Quote:
Original post by antareus
Quote:
 Original post by abnormaljust use c# and your pain will stop, as simple as that!

C# is not a panacea for poor software engineering.

it's a crutch, and will help you. Take Antareus's advice. I have experiance in both, and must say that if you really don't need speed, use C#. msdn.com -> visual studio 2005 beta -> visual C# express. :)

##### Share on other sites
Not to derail this thread, but I've never seen anything that really demonsrates the speed benefits of 'organized' vs. 'deorganized' memory allocation. Does anyone know of websites/articles about this?

##### Share on other sites
Quote:
Original post by Sagar_Indurkhya
Quote:
Original post by antareus
Quote:
 Original post by abnormaljust use c# and your pain will stop, as simple as that!

C# is not a panacea for poor software engineering.

it's a crutch, and will help you. Take Antareus's advice. I have experiance in both, and must say that if you really don't need speed, use C#. msdn.com -> visual studio 2005 beta -> visual C# express. :)
I don't think it's the right thing to call C# a crutch. Is C++ a crutch because it lets you write constructors and destructors that are called automatically, instead of you having to call them on your own? No. C++ lets you think on a higher plane of thought than C because the programmer is free from having to worry about some unimportant details. Similarly, C#, with its garbage collection, allows the programmer to think on an even higher level and thus make better and more innovative code. By the way, tests show that C# is almost as fast (and sometimes even faster) than C++. The only problem really is the overhead of the .Net framework.

##### Share on other sites
Quote:
 Original post by thedevdanIt is becoming painfully apparent that I can't use vectors on actual data; that I will need to use vectors of pointers. This is because I will be using interfaces extensively. Should I use boost's shared_ptr? What other options are there? Surely they don't manage memory all themselves?

Since nobody has brought this up yet, I figured I should mention it. Unless you have containers(vector, list, etc) of simple intrinsic types(int, float, etc) you should almost always prefer containers that hold pointers to your objects instead of containers of actual objects. The reason for this is that the STL makes a lot of copies of whatever the containers hold. It makes a copy when you pass something in, it makes a copy when you get something out, and it may make copies at other times, like when it re-sizes itself.

Now, whether you should use a container of raw pointers or a container of something like a shared_ptr has less to do with the container itself and more to do with how you intend to manage the data it holds. If you really feel that you need to be able to create/destroy this data in an ad-hoc manner any place in your application, then shared_ptr may be the way to go. If that's not the case, then raw pointers should be fine.

With that being said, whenever I need to access data at many places in my application I personally prefer the approach of having some kind of class that holds and manages this data for me. The other parts of the application can ask to look at the data, but they are not allowed to create/drestroy it directly. I think this makes it much easier to track down problems because it all happens in one place, instead of being scattered about your application.

One last reminder, make sure your classes destructors are virtual. Otherwise, as I'm sure you know, you'll run into problems if you go to delete pointers to your base class.

-John

##### Share on other sites
Quote:
 Original post by Tron3kI don't think it's the right thing to call C# a crutch. Is C++ a crutch because it lets you write constructors and destructors that are called automatically, instead of you having to call them on your own? No. C++ lets you think on a higher plane of thought than C because the programmer is free from having to worry about some unimportant details. Similarly, C#, with its garbage collection, allows the programmer to think on an even higher level and thus make better and more innovative code. By the way, tests show that C# is almost as fast (and sometimes even faster) than C++. The only problem really is the overhead of the .Net framework.

I would make a different comparison. Calling C# a crutch vs. C++ is like calling C a crutch vs. ASM. Is not every programming language above assembly a crutch?

There is a fine line between being a crutch and adding functionality however. :)

##### Share on other sites
Quote:
 I would make a different comparison. Calling C# a crutch vs. C++ is like calling C a crutch vs. ASM. Is not every programming language above assembly a crutch?There is a fine line between being a crutch and adding functionality however. :)

The difference is that C++ adds functionality without limiting your freedom in any way. In C++, you can implement anything you want, in any way you want, its as simple as that. You cant garbage collection? implement it! You want to perform pointer arithmetic? go ahead. You don't want to use classes? No problem. In C++, you can even create your own code stream and execute it (on-the-fly compilation).

The only real weakness of C++ is you, the programmer. Because in order to program efficiently in C++, you have to know what you're doing. I met many people who learned to "program" with visual basic and were very much scared of C++. I took a visual basic class once (I swear I had no choice) and I understood why: Visual basic is not logical. Everything is done for you, and nothing seems to follow logically. You just have to know the "language" by heart, and you can do one or two things "easily".

C++ is a language for the intuitive programmers who have a clue about the internal workings of a computer and operating system. C++ is for those who have a clue about what they want to program... Do I use C++ because I am afraid of using C? No. I use C++ because I know how to implement a C++ compiler in C.

So, back to the point, I fully agree with antareus:

Quote:
 C# is not a panacea for poor software engineering.

##### Share on other sites
C++ is far from intuitive.

C is pretty close, but C++ has a steep learning curve.

##### Share on other sites
Quote:
 Original post by antareusC++ is far from intuitive.C is pretty close, but C++ has a steep learning curve.

I learned programming starting from the basics. I first learned about the basics of how a microprocessor works, I then learned procedural languages, and quickly jumped to C++.

I found it very intuitive. Indeed, when you have an idea of how a microprocessor works, the concept of a pointer seems absolutely natural. Object-oriented design is also a natural way of thinking. In fact, if you look at the Quake 2 source code, you will see that they simply implement inheritance in C. They have structs containing data and function pointers. So a monster can contain all its states, and pointers to functions that define its behavior (in function of a struct containing all its states).

What mostly scares people about C++ is the syntax and the pointers. The syntax, just like any language, is a matter of getting used to... And the pointers, or references, whatever you call them, are an essential concept of pretty much any programming language that works. The syntax of C++ is actually quite nice when you think about it (and thats why so many languages are copying it). You get rid of useless keywords, like the then after the if. You can create code blocks, you can line up your code in multiple ways, for clarity... And you can make comments that span over multiple lines.

##### Share on other sites
Quote:
 Original post by Max_PayneI learned programming starting from the basics. I first learned about the basics of how a microprocessor works, I then learned procedural languages, and quickly jumped to C++.

C++ is a procedural language.
Quote:
 I found it very intuitive. Indeed, when you have an idea of how a microprocessor works, the concept of a pointer seems absolutely natural.

C++ is, as already mentioned, far from being intuitive.
It sets a lot of traps and requires a good amount of knowlegde about how the language works.
Quote:
 Object-oriented design is also a natural way of thinking.

It's one way to design programs. I'd be careful with such general statements. There are situations where OO is more obstructive than helpful. It's a Good Thing™, however, that you don't have to use it with C++, though.

Quote:
 And the pointers, or references, whatever you call them, are an essential concept of pretty much any programming language that works.

How many programming languages did you ever use?
Quote:
 The syntax of C++ is actually quite nice when you think about it (and thats why so many languages are copying it).

Actually C++ uses the same syntax as C.
Abnd when I think about C++ syntax I ask myself why there are so many beginner's stumbling over it. With Pascal its almost like - if it compiles correctly it most certainly does exactly what I expected. As opposed to C-like syntax where there are many little traps waiting for you to step into them.

C++ might be not that hard to learn - but it sure is very hard to master. Big projects require a good amount of software engineering and this should ideally be language-agnostic. The programming language is a tool, not a solution. Therefore it's good to know and use more than just one to enable you to choose the right tool for the job.

##### Share on other sites
Quote:
 Original post by Max_PayneWhat mostly scares people about C++ is the syntax and the pointers. The syntax, just like any language, is a matter of getting used to... And the pointers, or references, whatever you call them, are an essential concept of pretty much any programming language that works.
I disagree. C++ syntax is a relic, is inconsistent (why do we have terminating semi-colons on class/struct declarations but not on other block statements?) and is fairly primitive. Pointers aren't a strict necessity either. Other than twiddling individual bits, there isn't much specific benefit to them. C++'s type system has its pros and cons as well; some people prefer strong, dynamic typing while others prefer strong, static typing. C++ is weakly typed.

Quote:
 The syntax of C++ is actually quite nice when you think about it (and thats why so many languages are copying it).
No. So many languages copy C++ syntax because it is an extension of C syntax, which is the most popular and influential programming language on the planet (sorry, LISPers; C wins this battle). It has nothing to do with merit.

##### Share on other sites
Just as an aside: I've been trying to program in pure C and it literally takes the joy right out of programming. God I hate pure C. C++ is like sweet nectar compared to it.

##### Share on other sites
Quote:
 Original post by Tron3kJust as an aside: I've been trying to program in pure C and it literally takes the joy right out of programming. God I hate pure C. C++ is like sweet nectar compared to it.

There are a lot of programmers who will tell you the opposite.
Try to imagine you would have started with C#...

##### Share on other sites
Quote:
Original post by petewood
Quote:
 Original post by alniteI allocate/deallocate objects in one place, and pass constant pointers around (to prevent unintended deallocation).

It's okay to delete a constant pointer.

Oh, I was talking about pointers to constant objects.

##### Share on other sites
Quote:
Original post by alnite
Quote:
Original post by petewood
Quote:
 Original post by alniteI allocate/deallocate objects in one place, and pass constant pointers around (to prevent unintended deallocation).

It's okay to delete a constant pointer.

Oh, I was talking about pointers to constant objects.

Its ok to delete pointers to constant objects..

##### Share on other sites
Quote:
 Original post by TeknofreekIt makes a copy when you pass something in,

only when you add new elements but that makes sense.

Quote:
 Original post by Teknofreekit makes a copy when you get something out,

Wrong, all STL containers either return a reference and/or constant reference to there elements either directly or indirectly through iterators, the only time a copy of an element occurs if you don't declare variables being assigned/constructed on return as reference types.

And that comment about always using pointers for user-defined types is invalid, if you go crazy and have containers of pointers all over the place with-out any thought you'll more than likely hinder performance of your app by memory fragmentation because one the pointers will be copy constructed on the heap secondly you'll allocate instances at random/arbitrarty periods of time on the heap aswell.

You should only consider having container of pointers as a last resort, reasons being:

you need to have a heterogeneous container.

you need to have a container of polymorphic types where you need polymorphic behaviour.

user-defined type has a self-reference relationship it needs to store in a container which is its memeber aswell.

The type in question has made it's copy constructor & assigmenet operator private/protected because the type has no meaning of being copied for instance the I/O streams.

you wont to avoid the overhead of long copy construction but thats not really a good argument because you can do it all at initialization time or a more appropriate period of time.

##### Share on other sites
Quote:
Original post by Oluseyi
Quote:
 Original post by Max_PayneWhat mostly scares people about C++ is the syntax and the pointers. The syntax, just like any language, is a matter of getting used to... And the pointers, or references, whatever you call them, are an essential concept of pretty much any programming language that works.
I disagree. C++ syntax is a relic, is inconsistent (why do we have terminating semi-colons on class/struct declarations but not on other block statements?) and is fairly primitive. Pointers aren't a strict necessity either. Other than twiddling individual bits, there isn't much specific benefit to them. C++'s type system has its pros and cons as well; some people prefer strong, dynamic typing while others prefer strong, static typing. C++ is weakly typed.

Quote:
 The syntax of C++ is actually quite nice when you think about it (and thats why so many languages are copying it).
No. So many languages copy C++ syntax because it is an extension of C syntax, which is the most popular and influential programming language on the planet (sorry, LISPers; C wins this battle). It has nothing to do with merit.

Semicolon's on blocks end all type declarations, but yes, it's fairly inconsistent. Still, in some cases, it's the right tool for the job. It's all about choosing the right tool. Learn more languages, get more tools.

##### Share on other sites
Quote:
 Original post by CpManSemicolon's on blocks end all type declarations...
Do you know why? I do. Hint: they're not just type declarations.

@Teknofreek:
Actually, you should select or implement the correct allocator for your data type. Most people are ignorant and/or lazy, though, so they'd rather use pointers where semantically inaccurate and risk fragmentation.

##### Share on other sites
Quote:
Original post by darookie
Quote:
 And the pointers, or references, whatever you call them, are an essential concept of pretty much any programming language that works.

How many programming languages did you ever use?

C++, which has pointers and references. C, which has pointers. Java, which has references (wrapped pointers). ASM, which encourages you to play with memory addresses directly (natural pointers). I have also used QBasic and VB a long time ago. I don't remember if they have anything like pointers, but they are not the most efficient languages. And of course there is perl, but thats more of a scripting language. But anyhow, I know C# has garbage collection, but does it have references?

Quote:
 C++ might be not that hard to learn - but it sure is very hard to master. Big projects require a good amount of software engineering and this should ideally be language-agnostic. The programming language is a tool, not a solution. Therefore it's good to know and use more than just one to enable you to choose the right tool for the job.

If you have sufficient computer science knowledge, C++ will not be hard to master at all. Its actually very close to the way that the machine works, and does not try to hide things away from you. It will at most do some things automatically for you, but still leaves you the option not to resort to that. If you want to get into "Big projects", you should have enough computer science knowledge to understand how C++ works. Any competent software engineer should have this knowledge.

I appreciate the freedom that C++ gives me, and I do not find memory management to be a burden... It actually seems like something natural. Whatever ressources you request, you have to release at some point. But if memory management was to somehow become a problem, I could very easily setup my own memory management solution, and use it in the way I like. I see people complaining about memory leaks all the time, and pointers being the source of all problems in the world, but this is simply not true. Let me tell you, all bugs come from programming errors, not from the language you are programming in.