Skip to content

C++ Gurus

The forum for all discussions in C++ land.
1.3k Topics 8.5k Posts
  • 0 Votes
    6 Posts
    5k Views
    P

    Yes, it works fine now, thanks.

  • 0 Votes
    15 Posts
    6k Views
    F

    You can of course do something like

    @ typedef struct Object {
    void (*setData)(struct Object *, int);
    int (*data)(struct Object *);
    int m_data;
    } Object;

    Object *objectConstructor()
    {
    Object *o = malloc(sizeof(Object));
    memset(o, 0, sizeof(Object));
    o->setData = objectSetData;
    o->data = objectData
    return o;
    }

    void objectSetData(Object *this, int data)
    {
    this->m_data = data;
    }

    int objectData(Object *this)
    {
    return this->m_data;
    }
    @

    But that would arguably obscure your code for the simple fact that you have to explicitly pass the this argument:
    @
    Object *o = objectConstructor();
    o->setData(o, 5);
    printf("%d\n", o->data(o));
    @
    thereby making the function pointers look rather awkward.

  • More data help

    16
    0 Votes
    16 Posts
    6k Views
    J

    [quote author="Tobias Hunger" date="1303314614"]I'd just decide on one byte order to use in the file and stick with that. That avoids the bigendian bool and the if/else. Branches are always slow and avoiding them in a method that is called all the time is a good idea: Extracting ints from a data file smells like something that will happen rather often.

    Why do you need the data.mid()? That constructs a temporary object that is not necessary. @data.constData() + offset@ should work just as well as @data.mid(offset, 2).data()@ without creating a temporary object.

    I'd also try to use constData whenever possible. Using data() the way you do the compiler might think it needs to copy the temporary object you created since somebody might want to write into those bytes. Using constData is a very clear hint that this is not going to happen and the compiler can optimize the copy out. Of course it might be intelligent enough to do it for the data() case, too, but who wants to bet on the compiler being intelligent? ;-)
    [/quote]

    I have no control over the file and it has both bigendian and littleendian values (just to make my life hard) as it was a pc game that was ported to xbox 360 :s

    Also you're 100% right I'll use the data.constData() + offset as I have no real need for a temp object :) thanks again.

  • Question about binary data sotrage.

    7
    0 Votes
    7 Posts
    3k Views
    J

    I will thanks :D

  • [solved] Statement always null

    2
    0 Votes
    2 Posts
    2k Views
    A

    Because you are dividing integers. If you want to have a floating point result, you need to cast to a floating point number before dividing:

    @
    double newPos = static_cast<double>(ev->x())/90.0;
    @

  • Data variable scope

    4
    0 Votes
    4 Posts
    2k Views
    Z

    I would be tempted to use the singleton pattern for your top-level list. It is quick and easy to do and is easy to refactor if you decide to ever provide a non-gui version of your app.

  • [Moved] system() not running as expected

    5
    0 Votes
    5 Posts
    3k Views
    G

    "QProcess":http://doc.qt.nokia.com/4.7/qprocess.html should be a good alternative. You have control over stdin and stdout there.

  • Is Implicit Sharing always a good thing?

    14
    0 Votes
    14 Posts
    7k Views
    D

    [quote author="Gerolf" date="1301636313"]but the checks are cheap, compared to deep copying stuff.[/quote]

    Of course -- my point was that you have no control upon them and you pay for them even if your container is not shared at all. The same thing, mutatis mutandis, applies for any implicitly shared class.

    [quote]Having spent many years programming for hand held devices, dealing with low and no memory was always high on the list of the way we programmed. And so was important and was effectively dealt with in many/most situations. Do you really think it is acceptable for for a word processor or spreadsheet to crash due to low memory and loose sever hours of the users work? It is very difficult to add this sort of robustness to code after you have written it – it has to be done right from the start[/quote]

    You're absolutely right and I wasn't disagreeing with you. My point was: when a OOM happens, there's almost nothing you can safely do except from crashing the application. Anything you do is at risk of failing again because it tries to allocate more memory.

  • [Solved] Basic QIODevice subclass in Qt4

    49
    0 Votes
    49 Posts
    29k Views
    G

    also correct and a good idea. What you do not capture with this, is errors of storing itself.

  • Windoes Service Status &#63;

    6
    0 Votes
    6 Posts
    5k Views
    R

    Thanks alot,

    i have it. This is the working code.

    @LPCWSTR ServiceName = L"My ServiceName";

    SC_HANDLE hScManager = OpenSCManager(0, // local computer or add computer name here
    0, // SERVICES_ACTIVE_DATABASE database is opened by default.
    GENERIC_READ); // onyl read info
    if(0 != hScManager)
    {
    SC_HANDLE hSvc = OpenService(hScManager, // service manager
    ServiceName, // service name
    GENERIC_READ); // onyl read info
    if(0 != hSvc)
    {
    SERVICE_STATUS_PROCESS sInfo;

    DWORD bytesNeeded = 0; if(QueryServiceStatusEx(hSvc, // A handle to the service. SC_STATUS_PROCESS_INFO, // info requested (LPBYTE)&sInfo, // structure to load info to sizeof(sInfo), // size of the buffer &bytesNeeded)) { if(sInfo.dwCurrentState == SERVICE_RUNNING) { traymessage("test", "start!!!", 3); } else { traymessage("test", "stop!!!", 3); } } }

    }@

  • Bits manipulating question

    7
    0 Votes
    7 Posts
    8k Views
    F

    To control bits, you can use:

    | (binary or ) => sets bit & with negative mask => unset bit not that negative mask can be done using ~ (binary inversion) : result = result & (~BIT4) <<< unsets bit 4
  • [Moved] A question about pointers.

    14
    0 Votes
    14 Posts
    9k Views
    T

    [quote author="Volker" date="1300533129"][quote author="Taamalus" date="1300504867"]^ This may not work.
    http://www.codeguru.com/forum/archive/index.php/t-358371.html
    [/quote]

    What's the rationale behind this? To my knowledge even in poor old C (without ++) "0" is the all-valid constant for a null pointer (regardless of the internal representation for the actual machine). So

    @
    if(ptr == 0)
    doFancyThings();
    @

    is always valid code (See "comp.lang.c FAQ list, Question 5.2":http://c-faq.com/null/null2.html and "Question 5.5":http://c-faq.com/null/machnon0.html).
    [/quote]
    Thanks, I stand corrected. :) Still, there is no way I will use it, but from now on, just as a personal preference.
    http://en.wikipedia.org/wiki/Pointer_(computing)#Null_pointer
    this link is just to save face :D on my preferences

    Also thanks Gerolf! Re: Null Object Patterns, not for C++ but for LISP! Cheers! :)

  • Strange Behavior with pointers

    4
    0 Votes
    4 Posts
    2k Views
    G

    so, this is C++ basics:

    @
    PathNode* currNode;
    currNode = new PathNode(*node, 0.0, 0.0);
    @

    currNode is the pointer.

    @
    *currNode;
    @

    dereferences the pointer and returns a PathNode object (reference).

    @
    &currNode;
    @

    gives you the address of the pointer, so a PathNode**

    If you want to store the pointer in the map, use the pointer as in the list:

    @
    PathNode* currNode;
    currNode = new PathNode(*node, 0.0, 0.0);
    m_bhOpenList.Push(currNode);
    m_mapMasterList.insert(start, currNode);
    @

  • Static lib + static libs

    5
    0 Votes
    5 Posts
    4k Views
    T

    marswith: That tool is called ar. Mac, Linux and windows use this really simplistic packaging tool to store a set of object files into a static library. Of course all OSes use slightly different formats in the ar files they call static libraries;-)

  • 0 Votes
    3 Posts
    3k Views
    G

    Moved to the C++ Gurus forum, as it's not Qt specific.

  • C++ Tools List on Linux

    6
    0 Votes
    6 Posts
    5k Views
    Z

    [quote author="ryadav" date="1298140567"]If I want to monitor the memory usage of a specific process, what else can I use beside top?
    [/quote]
    ksysguard or one of a million other system monitors ;-)

    [quote author="ryadav" date="1298140567"]
    What is a good way to benchmark a process? I know netbeans has some cool stuff.
    [/quote]
    QTestLib has some support for benchmarking. Have a read of the "docs":http://doc.qt.nokia.com/latest/qtestlib-manual.html#creating-a-benchmark.

    Remember to run your benchmarks on a release build.

    You can also use valgrind --callgrind to get a trace of where your app spends each fraction of its time. You can view the output with kcachegrind. This will let you know where to focus your optimisation efforts.

    [quote author="ryadav" date="1298140567"]
    How do I determine what modules link to a binary or are loaded in a running process?

    Also is there a system logger on Linux? On Window I can use of OS Event Logging and Performance monitoring counters. Is there an equivalent on Linux?
    [/quote]

    To see what dynamic libraries are needed by an app at runtime use:
    @ldd /path/to/lib/or/app@

    You can use strace to get a trace of every syscall made by your application. Use it like:

    @strace myapp@

    The output will be very verbose so it is often useful to redirect it into a file that you can grep later.

    Another useful tool is "lsof" which will tell you about all of the open file handles your application has.

    Do not be afraid to make use of qDebug() statements. You can easily disable them in a release build by defining QT_NO_DEBUG_OUTPUT. ie just add

    @
    CONFIG(release, debug|release) {
    DEFINES += QT_NO_DEBUG_OUTPUT
    }
    @

    to your .pro file.

    I'm sure you'll pick up many more tips/tricks as you go along.

  • Overriding new and delete operator

    7
    0 Votes
    7 Posts
    8k Views
    D

    Full source here

    unittest_operatortest.pro
    @
    CONFIG += qtestlib console

    DEFINES += BUILD_QTILIB

    SOURCES += main.cpp
    SOURCES += unittest_operatortest.cpp

    HEADERS += unittest_operatortest.h
    @

    unittest_operatortest.h
    @
    #ifndef UNITTEST_OPERATORTEST
    #define UNITTEST_OPERATORTEST

    #include <QObject>
    #include <new>

    /*********************************************************************

    DECLARATIONS
    *********************************************************************/

    void * operator new(unsigned int size) throw (std::bad_alloc);
    void operator delete(void*) throw();
    void* operator new(size_t size, const std::nothrow_t&) throw ();
    void operator delete(void* ptr, const std::nothrow_t&) throw ();

    class Pointers : public QObject
    {
    public:
    static QList<void > instance();
    static void release();
    };

    #define MARK() Pointers::instance()->clear()
    #define NUM_POINTERS() Pointers::instance()->count()

    /*********************************************************************

    TEST CLASS
    *********************************************************************/

    class UnittestOperatorTest : public QObject
    {
    Q_OBJECT

    private slots: void init(); void cleanup(); // Test cases void testCanary();

    };

    #endif // UNITTEST_OPERATORTEST
    @

    unittest_operatortest.cpp
    @
    #include "unittest_operatortest.h"

    #include <QApplication>
    #include <QtTest/QTest>
    #include <QDebug>

    /*********************************************************************

    POINTER CLASS IMPLEMENTATION
    *********************************************************************/

    static QList<void > globalAllocationList = NULL;

    QList<void > Pointers::instance()
    {
    if ( !globalAllocationList ) {
    globalAllocationList = static_cast<QList<void*>*>(malloc(sizeof(new QList<void >)));
    new (globalAllocationList) QList <void>;
    }
    return globalAllocationList;
    }

    void Pointers::release()
    {
    globalAllocationList->~QList();
    free(globalAllocationList);
    globalAllocationList = NULL;
    }

    /*********************************************************************

    TEST CASES
    *********************************************************************/

    void UnittestOperatorTest::init() {
    MARK();
    }

    void UnittestOperatorTest::cleanup() {
    }

    void UnittestOperatorTest::testCanary() {
    QVERIFY(true);

    // Makes sure that environment works for new and delete -operators. QCOMPARE(NUM_POINTERS(), 0); int *i = new int(2); QCOMPARE(NUM_POINTERS(), 1); delete i; QCOMPARE(NUM_POINTERS(), 0); QWidget *w = new QWidget(); QCOMPARE(NUM_POINTERS(), 1); delete w; QCOMPARE(NUM_POINTERS(), 0);

    }
    @

    main.cpp
    @
    #include "unittest_operatortest.h"

    #include <QtTest/QTest>
    #include <QApplication>

    /*********************************************************************

    OVERRIDE CODE
    *********************************************************************/

    void * operator new(unsigned int size) throw (std::bad_alloc)
    {
    void *ptr = (void *)malloc(size);
    Pointers::instance()->append(ptr);
    return(ptr);
    };

    void operator delete(void *p) throw()
    {
    Pointers::instance()->removeAll(p);
    free(p);
    };

    void * operator new(unsigned int size, const std::nothrow_t&) throw ()
    {
    void *ptr = (void *)malloc(size);
    Pointers::instance()->append(ptr);
    return(ptr);
    };

    void operator delete(void *p, const std::nothrow_t&) throw()
    {
    Pointers::instance()->removeAll(p);
    free(p);
    };

    /*********************************************************************

    MAIN FUNCTION
    *********************************************************************/

    int main(int argc, char *argv[])
    {
    QApplication app(argc, argv);
    int ret = 0;

    UnittestOperatorTest testableClass; ret = QTest::qExec(&testableClass, argc, argv&#41;; return ret;

    }
    @

  • Calculating Adjacent matrix

    2
    0 Votes
    2 Posts
    3k Views
    A

    Sorry, this is not the place to ask for explanations on code you found somewhere on the web. How about asking the author of that code?

    For general information on how to calculate an adjacency matrix, I'd like to refer you to the math section of your nearest university library, the almighty interweb or I'd like to suggest you simply use the Boost::graph library.

  • [SOLVED] Random Number Generation

    3
    0 Votes
    3 Posts
    23k Views
    C

    LOL! Do you realize how long I have stared at that stupid line and realized what I was looking at?!?!

    Geez. Perhaps I should go into project management!

    ;-))

    My apologies to any project managers out there.

  • 0 Votes
    8 Posts
    6k Views
    G

    [quote author="mcosta" date="1296741507"]I think allocate Tetrahedron on the stack is wrong.

    When the AffectCube constructor returns, the Tethraedron instance is destroyed[/quote]

    ripspinner wrote that already in his last comment and it works.

    Please read a thread until its end and only post comments if you have something new to add. Thanks.