Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Harik
Sep 9, 2001

From the hard streets of Moscow
First dog to touch the stars


Plaster Town Cop
Stupid C++ style question:

For a producer/consumer threaded pattern, is it sane to cause the blocking .next() to throw during shutdown? There's other ways to do it (if (work.next(&foo)) break; ), so I was wondering if there was a consensus on best practice.

Something like:
C++ code:
void threaded_consumer() {
        try {
                while(1) {
                        foo * foo=work.next();
                        // work on foo
                        delete foo;
                }
        } catch ( NoMoreWork &w ) {
                printf("Shutting down consumer thread: %s", w.what());
        }
}
The idea is it'd be thrown when the producers have signaled they're finished and the queue is empty.

Adbot
ADBOT LOVES YOU

csammis
Aug 26, 2003

Mental Institution
I wouldn't use an exception for this because it's not an exceptional case. A producer/consumer should naturally be able to handle the situation where a consumer runs out of work to do.

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
Have foo.next() return null if there's no work and loop on that?
code:
while(foo * foo=work.next()) {
    // do work
    delete foo;
}

mmm11105
Apr 27, 2010
As someone who programa a lot in C#/Python/JS/A little C/etc. but wants to learn C++, is there a good book/website that is updated for C++11?

Contains Acetone
Aug 22, 2004
DROP IN ANY US MAILBOX, POST PAID BY SECUR-A-KEY

Contains Acetone fucked around with this message at 17:37 on Jun 24, 2020

Harik
Sep 9, 2001

From the hard streets of Moscow
First dog to touch the stars


Plaster Town Cop

csammis posted:

I wouldn't use an exception for this because it's not an exceptional case. A producer/consumer should naturally be able to handle the situation where a consumer runs out of work to do.

Yeah. I was asking about it because it's a once-per-run situation but realistically exceptions should be for things that shouldn't ever happen. From a C background, I generally propagate errors via negative return/null for pointers anyway, so I don't end up using them aside from catching library throws. I've spent too much of my time on tiny-tiny embedded (16k rom 256bytes sram) lately, trying to make sure my higher-level patterns are still sane.

Combat Pretzel posted:

Have foo.next() return null if there's no work and loop on that?
code:
while(foo * foo=work.next()) {
    // do work
    delete foo;
}

You're absolutely right, and I was overthinking it trying to support queue<int>, which isn't used for anything but programming exercises.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

Contains Acetone posted:

Is there a light weight cross-platform C or C++ library for dealing with large (>4 GB) files? I'm currently using Microsoft's own _fseeki64 and friends but I'd like to port VisualRBM's backend to other operating systems.

Everything but windows uses fseeko/ftello for that. There's no particular need for a library to wrap it.

pseudorandom name
May 6, 2007

Well, you still have to deal with off_t being a 32-bit integer on 32-bit platforms.

That Turkey Story
Mar 30, 2003

Harik posted:

Stupid C++ style question:

For a producer/consumer threaded pattern, is it sane to cause the blocking .next() to throw during shutdown? There's other ways to do it (if (work.next(&foo)) break; ), so I was wondering if there was a consensus on best practice.

Something like:
C++ code:
void threaded_consumer() {
        try {
                while(1) {
                        foo * foo=work.next();
                        // work on foo
                        delete foo;
                }
        } catch ( NoMoreWork &w ) {
                printf("Shutting down consumer thread: %s", w.what());
        }
}
The idea is it'd be thrown when the producers have signaled they're finished and the queue is empty.

Don't use an exception for this. A couple of other concerns here -- is there a reason you are doing a busy loop? It would likely be better to have a version of next() that blocks and waits for work/shutdown (I.E. internally waits on a condition variable). Also, get rid of those raw pointers and either replace them with std::unique_ptr or (probably better) return something like a boost::optional.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

pseudorandom name posted:

Well, you still have to deal with off_t being a 32-bit integer on 32-bit platforms.

Building with -D_FILE_OFFSET_BITS=64 fixes that.

Sauer
Sep 13, 2005

Socialize Everything!

mmm11105 posted:

As someone who programa a lot in C#/Python/JS/A little C/etc. but wants to learn C++, is there a good book/website that is updated for C++11?

The C++ Programming Language written by the guy who invented the language was recommended to me earlier in the thread and its pretty good. The first part of it is a quick run through of the language tailored for people who already know how to program and the rest of the book goes into an almost autistic level of detail about how it works. Stroustrup intended for the book to not just be an instructional textbook but also a definitive reference for the language. The E-Book version of it that Amazon is selling is well formatted but you'll need to reduce the font size in your reader or read in landscape mode if you want the code examples to be readable without comments wrapping to the next line.

Tres Burritos
Sep 3, 2009

Is it stupid to be doing C++ in linux with Sublime Text? If not, can someone recommend a debugger that has a GUI and is pretty well documented? There seem to be a lot of GDB frontend options out there.
If it is stupid to be using a text editor instead of an IDE could someone point me in the direction of a Linux IDE that isn't Eclipse?

Sauer
Sep 13, 2005

Socialize Everything!
kDevelop was pretty sweet in the limited time I messed around with it.

GeneralZod
May 28, 2003

Kneel before Zod!
Grimey Drawer

mmm11105 posted:

As someone who programa a lot in C#/Python/JS/A little C/etc. but wants to learn C++, is there a good book/website that is updated for C++11?

Tres Burritos posted:

Is it stupid to be doing C++ in linux with Sublime Text? If not, can someone recommend a debugger that has a GUI and is pretty well documented? There seem to be a lot of GDB frontend options out there.
If it is stupid to be using a text editor instead of an IDE could someone point me in the direction of a Linux IDE that isn't Eclipse?

There was a bit of discussion on both of these topics a few weeks back:

http://forums.somethingawful.com/showthread.php?threadid=2773485&userid=0&perpage=40&pagenumber=379

Re: books - several people recommended The C++ Programming Language, 4th Edition and C++ Primer (5th Edition), both of which are intended for people who can already program but wish to learn C++ and both of which have been updated from the ground up to use C++11.

Re: IDEs - I would guess that the majority of development under Linux is done using Vim or Emacs but I personally always use KDevelop, which has excellent C++ navigation/ completion and, in 4.12+ at least, a pretty sound Vim emulation mode (plug, plug).

GeneralZod fucked around with this message at 15:30 on Jan 5, 2014

Hughlander
May 11, 2005

Tres Burritos posted:

Is it stupid to be doing C++ in linux with Sublime Text? If not, can someone recommend a debugger that has a GUI and is pretty well documented? There seem to be a lot of GDB frontend options out there.
If it is stupid to be using a text editor instead of an IDE could someone point me in the direction of a Linux IDE that isn't Eclipse?

There are sublime text plugins for that. When I started doing some very advanced android NDK work I dropped eclipse and just used Sublime Text as my editor and raw gdb as my debugger and it worked great. Take a look at SublimeClang or Completion plugins if you want to make it an IDE. SublimeGDB if you want to add a debugger. I find that Sublime Text has the fastest navigation in a large project over any alternative so I still use it for some things.

Deep Dish Fuckfest
Sep 6, 2006

Advanced
Computer Touching


Toilet Rascal

mmm11105 posted:

As someone who programa a lot in C#/Python/JS/A little C/etc. but wants to learn C++, is there a good book/website that is updated for C++11?

I'll have to dissent and say I'm not sure if "The C++ Programming Language" is appropriate for someone who doesn't already know C++. It's very dry, even for a programming language book, and that includes the tutorial section, which I don't think is enough by itself to really make use of what C++ adds to C. I guess whether the book is going to be useful for someone comes down to two things: whether you do better with a more hand-on or a more theory oriented approach to learning, and whether you're already comfortable with C and other relatively low-level languages.

If you're good at learning by reading text and code that's crafted to be the minimum required to show a feature, then the book might be for you. If you like books that have relatively realistic examples (without being design pattern and software engineering books), then it's unlikely to be the book for you. The book does contain one design example which takes a whole chapter (designing a matrix class), but it comes in about 750 pages into the book, and it's not something you can just skip to without reading pretty much all of the previous material. I think it's actually the last chapter before the book starts examining the standard library features, and the example is largely focused on templates, arguably the most complex part of the language. I also recall another larger example where there's an expression parser built (for a desktop calculator, I think), but other than that, it's largely going to be small code fragments.

The other thing to consider is how good your understanding of memory organization and other relatively low-level concepts is. To an extent, this is all something that should be kept in mind when writing C and C++ code, and the book is going to start throwing memory layout diagrams at you as soon as you get to the tutorial section on classes, and maybe earlier. Basically, if pointers in C are a concept which isn't entirely clear to you, then the book is probably not for you. I guess it depends what you mean by "A little C"; people tend to have different definitions.

Really, I think it's an excellent book if you want to push your knowledge of C++ further, or get up to date with C++11, but I'm not so sure about learning C++ from it.

MrMoo
Sep 14, 2000

DSauer posted:

kDevelop was pretty sweet in the limited time I messed around with it.

I'll have to try this, otherwise DDD is pretty much the only sensible option:

http://www.gnu.org/software/ddd/

Optimus Prime Ribs
Jul 25, 2007

This is more of a question regarding Microsoft's C++ compiler than C++ itself, but this seemed like the best place to ask.

G++ complains about the lack of "typename" before Ty::Thing in this contrived example code, as I would expect:
code:
template <class Ty>
struct Foo {
    typedef Ty Thing;
};

template <class Ty>
void bar(Ty whatever) {
    Ty::Thing a;
}

int main() {
    bar(Foo<int>());
}
However, if I plop the code into Visual Studio 2012 it compiles just fine. Does MVC++ have different rules, or is it just inserting "typename" for me?

OneEightHundred
Feb 28, 2008

Soon, we will be unstoppable!
If it compiles fine in MSVC and fails everywhere else, it's usually MSVC's compiler being non-compliant. It has a bunch of quirks like that (i.e. permitting incompatible ternary operands, qualified method names in class declarations, etc.)

Optimus Prime Ribs
Jul 25, 2007

I had a feeling it was just Microsoft ignoring standards and doing their own thing, which sucks because I like writing C++ with Visual Studio, but I don't want to write non-standard code. Guess I can just use G++ to ensure I didn't miss any little things like that.

raminasi
Jan 25, 2005

a last drink with no ice
It's possible that there's something you can set to make it not do that, but I wouldn't hold my breath.

Slurps Mad Rips
Jan 25, 2009

Bwaltow!

GrumpyDoctor posted:

It's possible that there's something you can set to make it not do that, but I wouldn't hold my breath.

The option to force msvc to disable language extensions is /Za. However it's use is not recommended because it breaks all kinds of poo poo and they stopped testing the standard library with it since VS10.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed

Optimus Prime Ribs posted:

I had a feeling it was just Microsoft ignoring standards and doing their own thing
It's not; it's just a technical limitation of their C++ frontend that they've working on fixing. Proper two-phase lookup isn't really possible with their approach of only building ASTs for a single statement at at time (which is something that made more sense to do when it was originally written in the early 80s).

Optimus Prime Ribs
Jul 25, 2007

Well if that's the case I can't fault them for just making an "oops".

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.
llvm/clang 3.4 come out today (downloads aren't up yet, though). Notable additions are clang-cl, an experimental drop-in replacement for Visual Studio's cl, and clang-format for automatic C/C++/Obj-C formatting.

Plorkyeran
Mar 22, 2007

To Escape The Shackles Of The Old Forums, We Must Reject The Tribal Negativity He Endorsed
And complete support for the current C++14 draft.

Paolomania
Apr 26, 2006

Tres Burritos posted:

Is it stupid to be doing C++ in linux with Sublime Text? If not, can someone recommend a debugger that has a GUI and is pretty well documented? There seem to be a lot of GDB frontend options out there.
If it is stupid to be using a text editor instead of an IDE could someone point me in the direction of a Linux IDE that isn't Eclipse?

I'm generally a VIM guy, but even I use EMACS as an IDE on Linux. "Meta-x gdb" to start GDB, then "Meta-x gdb-many-windows" to get a nice WinDbg-style 5-6 window layout.

Boz0r
Sep 7, 2006
The Rocketship in action.
Can anyone recommend some good static analysis tools for Visual Studio?

High Protein
Jul 12, 2009
On a project I'm dealing with a library that communicates with a PLC. It returns some PLC value, which can be a signed char, int or short, as a signed int. However, the value is not sign extended, so the short value -1 results in 0x0000ffff being returned; are my comments below correct assuming the libary DOES convert the value to the PC's endianness? Also, is it right that if instead of the client endianness it returns the PLC's endianness, I would have to use the result3 or result6 method (perhaps compensated for big endian)?

Originally my colleagues suggested the 'result1' method, but we ended up going with the shifts, 'result4'.

One thing that kind of trips me up about result6 is that people paraphrase the standard as guaranteeing that you can reinterpret_cast to some other type, then cast back, and be assured you'll be able to access your original value. However, in this case, there's no 'original value' of type short* to speak of.

code:
void main()
{
	int input = 0x0000ffff; //this was a (signed) short returned by some hardware, we want to return an int.

	int result1 = static_cast<short>(input); //Undefined: signed overflow

	int result2 = *reinterpret_cast<short*>(&input); //Endianness issue, improper aliasing
	
	short temp;
	memcpy(&temp, &input, sizeof(short));
	int result3 = temp; //endianness issue, otherwise correct

	int result4 = input << 16 >> 16; //correct

	union
	{
		int i;
		short s;
	} Union;
	Union.i = input;
	int result5 = Union.s; //improper aliasing, endianness issue

	char* pc = reinterpret_cast<char*>(&input);
	int result6 = *reinterpret_cast<short*>(pc);   //endianness issue but no incorrect aliasing as we go via char*
}

High Protein
Jul 12, 2009

Boz0r posted:

Can anyone recommend some good static analysis tools for Visual Studio?

If you've got access to one of the fancier VS editions, they've got a built-in analyzer; might be easy to try.

At work we use PC-Lint in combination with Visual-Lint, and though it works fine it's got several disadvantages: you need two products, c++11 support is spotty (even has issues with the 'override' keyword). I don't remember why they chose it, I'll have to ask. Maybe because of the VS integration, which is quite good.

I've used PVS-Studio and was impressed by the clarity of its explanations for various issues, and it seems to do a good job of detecting suspect patterns that aren't really language issues, like copy/paste errors.

Finally, the Clang static analyzer can be used with VS and is free.

Dren
Jan 5, 2001

Pillbug

Tres Burritos posted:

Is it stupid to be doing C++ in linux with Sublime Text? If not, can someone recommend a debugger that has a GUI and is pretty well documented? There seem to be a lot of GDB frontend options out there.
If it is stupid to be using a text editor instead of an IDE could someone point me in the direction of a Linux IDE that isn't Eclipse?

I asked about C++ IDEs a month or two ago and someone pointed me at Kdevelop. I had been using Eclipse with the CDT for doing code diving and I was getting sick of it because the C++ parser didn't work very well on the codebase I work on. I switched to Kdevelop and have not looked back. It is awesome. Pretty much parses all of the code in this project and makes it all explorable (like you can click on a function and go right to its definition). The autocomplete stuff works well too. There are a few quirks like you have to put the include paths you're using into a .kdev_include_path file instead of configuring them in a gui somewhere. If someone knows how to get the tango-dark theme for Kdevelop, that would be really great. The themes stuff seemed like sort of a pain so I haven't messed with it.

I don't build or debug with Kdevelop so I can't say if it's good at those things. Back when I used to debug a lot I used the gdb integration in emacs and it was excellent.

Marta Velasquez
Mar 9, 2013

Good thing I was feeling suicidal this morning...
Fallen Rib
I'll vouch for KDevelop's gdb integration. It's pretty good for C projects. Create a debug "launch configuration" under the Run menu to set it up.

I use custom Makefiles for my projects. I've never had a problem with KDevelop for that, either.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

High Protein posted:

code:
	int result1 = static_cast<short>(input); //Undefined: signed overflow

Overflow in an integer conversion has its own rule in the standard(s) and doesn't fall under the general rule about expressions with unrepresentable results. The result that it's merely implementation-defined, not undefined, and that only because the standards don't specify a signed integer format. In practice, on two's complement platforms, it's always defined as a truncation/reinterpretation.

In other words, just use the obvious cast.

Qwertycoatl
Dec 31, 2008

High Protein posted:

code:
	int result4 = input << 16 >> 16; //correct

This is actually undefined - you aren't allowed to left-shift a signed integer such that anything gets put into the sign bit.

Also the right-shift (assuming the compiler did what you wanted with the left-shift) is implementation-defined. On most platforms it will do what you want but some will zero the sign bit instead of sign-extending.

High Protein
Jul 12, 2009
Thanks guys.

Yeah, I should have said implementation defined behavior, and of course in practice the cast works just fine; both Clang and MSVC release builds return the proper -1 for each example, though that's all on x86.

Interesting on the shift, it seemed like the best option to me; both behaviors surprise me, though I can imagine some platforms don't have an arithmetic left shift instruction.

The shift has an additional advantage though: instead of having different cases for data that uses the full int, a short or a char we can just shift by (sizeof(int)-DataTypeSize)*8, where we can set DataTypeSize to e.g. sizeof(short) at some earlier point.

Edit: it also surprises me that the left shift is undefined, while merely overflowing a signed int is implementation defined.

Does that mean the most pedantically correct method is the memcpy? Looking at result4 and result6 again it seems they're both equally wrong, as the reinterpret_cast to char* is allowed, but not to anything other than back to int* from there.

High Protein fucked around with this message at 13:17 on Jan 11, 2014

nielsm
Jun 1, 2009



Most likely, whatever you use to read those bits off the external port puts them into your int in host byte order. Most normal implementations of C (anything you will encounter short of perhaps some embedded or ancient systems) will cast a 32 bit signed int to a 16 bit signed short by truncation, blindly taking the 16 least significant bits and handling them as a short. That would be independent of the system byte order. If you have an int written as 0x12345678 and cast it to a short then the result will be 0x5678 regardless of the system byte order, despite them having in-memory layouts of respectively 78-56-34-12 and 12-34-56-78.
On the other hand, if you start messing around with memcpy then endianness will certainly be an issue.

If you really need to be super portable, then your first priority should be to figure out how that library you're using to get those data actually returns them. If they can't document that in a sensible way, switch to something else.

OneEightHundred
Feb 28, 2008

Soon, we will be unstoppable!
Yet another dumb aliasing question. Assuming something like:

code:
struct A
{
    int value;
};

struct B
{
    A a;
};

int func1(A *a, const B *b, int c)
{
    a[1].value = c;
    return b[1].a.value;
}

int func2(A *a, const B *b, int c)
{
    reinterpret_cast<A*>(reinterpret_cast<char*>(a) + sizeof(A))->value = c;
    return reinterpret_cast<const B*>(reinterpret_cast<const char*>(b) + sizeof(B))->a.value;
}
... am I correct in assuming that these two aren't the same, because func1 would cause the compiler to assume that a[1] is contained within an array of A and couldn't be contained within a B, and so could consider the store and read reorderable, but the second would always have to perform the read and write in that order because there's nothing that would rule out the A written to in the first line being contained in the B at the second?

OneEightHundred fucked around with this message at 22:56 on Jan 12, 2014

FamDav
Mar 29, 2008
First, your code doesn't compile so they have the same behavior.

Second, aliasing rules work on types, not memory locations.

Third, regarding if a pointer can alias a member of another pointer

Some Dude posted:

An aggregate (struct or class) or union type can alias types contained inside them.
(Example: If a function gets passed a pointer to an int, and a pointer to a struct or union
containing an int, or possibly containing another struct or union containing an int, or
containing...ad infinitum, it's possible that the int* points to an int contained inside the
struct or union pointed at by the other pointer.)

so in either case, the compiler is not allowed to reorder.

hooah
Feb 6, 2006
WTF?
For my algorithms class, the TA gave us a main to test the two sorting algorithms we're supposed to right. MSVC gives me a few warnings for the TA's code. The first comes from bool result *= verifySort(x); (verifySort just checks that our algorithm is right, and returns a bool). The message for this line is "'*=' : unsafe use of type 'bool' in operation" The second refers to the same line, and the message is "'int' : forcing value to bool 'true' or 'false' (performance warning)". What do these two messages mean? And what is meant by multiplication on a boolean?

Adbot
ADBOT LOVES YOU

Hughlander
May 11, 2005

hooah posted:

For my algorithms class, the TA gave us a main to test the two sorting algorithms we're supposed to right. MSVC gives me a few warnings for the TA's code. The first comes from bool result *= verifySort(x); (verifySort just checks that our algorithm is right, and returns a bool). The message for this line is "'*=' : unsafe use of type 'bool' in operation" The second refers to the same line, and the message is "'int' : forcing value to bool 'true' or 'false' (performance warning)". What do these two messages mean? And what is meant by multiplication on a boolean?

It's just a hack Id expect a TA to find clever. By treating the bool as an int with true being nonzero and false being zero if any return is false you are multiplying by zero and now the bool will always be false for the rest of the operations.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply