lundi 31 octobre 2016

C++11 alias templates

I ran to some problems with c++11 alias templates. As you can see below, I want to create an alias to A::B from class C. Before instantiation is made the compiler (gcc 6.1) cannot assert that V has a member type B, therefore giving the error:

error: expected ‘;’ before ‘<’ token  
template<typename ValueT> using B = typename V::B<ValueT>;

Does not his go against the usual way templates are dealt with in C++, that is assuming that the template type provides all necessary functionalities until proven otherwise by an instantiation?

template<typename T> class A{
    T a;
public:
    template <typename ValueT> class B {
        ValueT b;
    };
};

template <typename V = A<int>> class C {
public:
    template<typename ValueT> using B = typename V::B<ValueT>;
};

How should a weak_ptr be initialized in a class constructor that receives a shared_ptr?

I have a class that receives a shared pointer in its constructor and stores it in a weak pointer but I'm not sure how (and where) to do this conversion.

class A {
    public:
        A(std::shared_ptr<B> Bptr);

    private:
        std::weak_ptr<B> m_Bptr;
};

Should I convert the shared_ptr before passing to the constructor or not?

Does passing the shared_ptr to the weak_ptr through an initialization list like this A(std::shared_ptr<B> Bptr) : m_Bptr(Bptr) { } works as expected or I need to explicitly convert in the body of the constructor?

compile error on converting std::bind object to std::function

#include <iostream>
#include <functional>

using FuncType = std::function<std::string()>;

template <typename... Args>
std::string AnalysisRaw(const std::string& tmp, const Args&... args)
{
    return std::string();
}

template <typename... Args>
inline void log(const char* fmt, const Args&... args)
{
    std::string tmp = "";

    FuncType type = std::bind(&AnalysisRaw<Args...>, tmp, args...);
}

int main()
{
    log("xxx", "yyy");

    return 0;
}

The code above is meaningless, just to show the problem.

There is a compile error says that "cannot convert ..." and "No constructor could take the source type, or constructor overload resolution was ambiguous".

However, if I call "log" function such as

log("xxx", (const char*)"yyy");

there is no compile error. It seems that const char (&)[] performs differently against const char*

std::invoke no matching overloaded function found error given in VS 2015

I'm very new to C++ and SDL and I am trying to create a thread that constantly updates the screen but the I keep getting the following errors:

'std::invoke no matching overloaded function found'

and

'Failed to specialize function template 'unknown-type std::invoke(Callable &&,_Types&&...)''

main.cpp

  int main(int argc, char **argv) {
    using namespace std::placeholders;
    bool gameover = false;
    int test;
    std::string filepath = getResourcePath("Lesson1");

    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {               // Intializes SDL functionality
        std::cout << "Could not start SDL" << std::endl;
        std::cin >> test;
        return 1;
    }
    else {
        std::cout << "SDL started successfully!" << std::endl;
    }

    viewWindow window;                                  // Class representing the window in which the program is run.


    SDL_Renderer *render = window.render();         // Pointer to the renderer used to draw images to the window.
    if (render == nullptr) {
        std::cout << "There was an error creating the renderer" << std::endl << SDL_GetError() << std::endl;
        std::cin >> test;
        return 1;
    }

    SDL_Surface *emptySurface = window.blankSurface();   // Temp surface to draw background to
    if (emptySurface == nullptr) {
        std::cout << "Unable to create a blank surface " << std::endl << SDL_GetError() << std::endl;;
        std::cin >> test;
        return 1;
    }

    surfaces background;

    background.filename = "grass.bmp";

    SDL_Surface *backgroundSurface = background.loadSurface(filepath); 
    if (backgroundSurface == nullptr) {
        std::cout << "Unable to create background surface" << std::endl << SDL_GetError() << std::endl;
        std::cin >> test;
        return 1;
    }

    SDL_Rect backgroundRect;

        SDL_Texture *backTexture = background.blitBack(render, backgroundRect, backgroundSurface, emptySurface);



        player player;

        SDL_Rect playerRect;
        playerRect.x = 320;
        playerRect.y = 240;
        playerRect.h = 16;
        playerRect.w = 16;


        SDL_Texture *playerTexture = player.createPlayerTexture(render, filepath);
        if (playerTexture == nullptr) {
            std::cout << "Could not load player texture" << std::endl << SDL_GetError() << std::endl;
            std::cin >> test;
            return 1;
        }

        while (!gameover) {
            std::thread t((&viewWindow::refreshWindow, render, playerRect, backTexture, playerTexture));
            playerRect.x = player.moveX(playerRect);
            playerRect.y = player.moveY(playerRect);
            t.join();
        }


    return 0;
   }

viewWindow.h

   #pragma once
#ifndef VIEWINDOW_H
#define VIEWWINDOW_H
#include "SDL.h"



class viewWindow                // Class representing the window.
{
private:
    char winName[45] = "Game Test";
    int winWidth = 640;
    int winHeight = 480;
    int xPos = 960;
    int yPos = 540;


public:


     SDL_Window *view();    // Intializing funtions for creating the window and renderer.

     SDL_Renderer *render();

     SDL_Surface *blankSurface();

    void refreshWindow(SDL_Renderer *renderer, SDL_Rect &playerRect, SDL_Texture *backtex, SDL_Texture *playertex);

};


#endif

viewWindow.cpp

   #include "viewWindow.h"
#include <string>
#include "SDL.h"


SDL_Window *viewWindow::view()      
{
    SDL_Window *createdwindow = SDL_CreateWindow(winName, xPos, yPos, winWidth, winHeight, SDL_WINDOW_SHOWN);
    return createdwindow;

}

SDL_Renderer *viewWindow::render() {

    SDL_Renderer *render = SDL_CreateRenderer(view(), -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    return render;
}

SDL_Surface *viewWindow::blankSurface() {
    SDL_Surface *blacksurface = SDL_CreateRGBSurface(0, winWidth, winHeight, 32, 0, 0, 0, 0);
    return blacksurface;
}

void  viewWindow::refreshWindow(SDL_Renderer *renderer, SDL_Rect &playerRect, SDL_Texture *backtex, SDL_Texture *playertex) {
    while (true) {
        SDL_RenderClear(renderer);
        SDL_RenderCopy(renderer, backtex, NULL, NULL);
        SDL_RenderCopy(renderer, playertex, NULL, &playerRect);
        SDL_RenderPresent(renderer);
    }

}

Able to reference functions but, not classes from a Namespace

I am able to reference functions from a namespace but, not classes. Here is the namespace file SeqLib/FermiAssembler.h"

#ifndef SEQLIB_FERMI_H
#define SEQLIB_FERMI_H

#include <string>
#include <cstdlib>
#include <iostream>

namespace SeqLib 
{

    void print_my_name(){ std::cout << "It's Crt" }
    class FermiAssembler {
    public:
        FermiAssembler();
    };
}

I am able to call print_my_name() via SeqLib::print_my_name() but, not able to reference the FermiAssembler class via SeqLib::FermiAssembler f

What is the problem?

QSqlQuery placeholder for table

Here is says placeholders do not work for table name. Why?

QSqlQuery query(db);
qDebug() << query.prepare("SELECT :parameter FROM :table");
query.bindValue(":parameter", parameter);
query.bindValue(":table", table);

How to overcome that issue?

How to have Allegro on CLion?

I looked everywhere but I can't see to find the answer. Is there a way to put Allegro onto CLion? I have tried looking all over stackoverflow, google, and youtube. I just can't find it. If you guys can help me it will be appreciated. Thank you so much.

Does being std::move'd affect references?

I'm trying to make sense of some code I'm looking at, and one thing that I noticed is that one class keeps a reference to this one object in a reference member, while some other code move constructs it.

I'm curious how those play together. Is a reference member still valid if the underlying object is the source (or target) of a std::move operation?

How about if I happen to know that the underlying object has all its move operators custom defined to just std::move all its members? Presumably in that case the reference to it is valid when the source object being referenced is valid, and not valid when it isn't, right?

Class A member template function declared as friend in class B can't access private members of class A (Clang only)

Sorry for the title, it is a mouthful, but I could not find a good compromise between readable and specific.

Please take a look to this code snippet. I know it does not make much sense, it is just intended to illustrate the problem I am encountering:

#include <iostream>
using namespace std;

struct tBar
{
    template <typename T>
    void PrintDataAndAddress(const T& thing)
    {
        cout << thing.mData;
        PrintAddress<T>(thing);
    }

private:
    // friend struct tFoo; // fixes the compilation error

    template <typename T>
    void PrintAddress(const T& thing)
    {
        cout << " - " << &thing << endl;
    }
};

struct tFoo
{
    friend void tBar::PrintDataAndAddress<tFoo>(const tFoo&);
    private:

    int mData = 42;
};

struct tWidget
{
    int mData = 666;
};

int main() 
{
    tBar bar;
    bar.PrintDataAndAddress(tWidget()); // Fine

    bar.PrintDataAndAddress(tFoo()); // Compilation error

    return 0;
}

The code above triggers the following error:

source_file.cpp:10:3: error: 'PrintAddress' is a private member of 'tBar' PrintAddress(thing); source_file.cpp:42:6: note: in instantiation of function template >specialization 'tBar::PrintDataAndAddress' requested here bar.PrintDataAndAddress(tFoo()); // Compilation error source_file.cpp:17:7: note: declared private here void PrintAddress(const T& thing)

but only in Clang++. GCC and MSVC are fine with it (you can quickly test that by pasting that code in http://ift.tt/2bynScT)

It seems as if tBar::PrintDataAndAddress<tFoo>(const tFoo&) is using the same access as tFoo, where it is befriended. I know this because befriending tFoo in tBar fixes this issue. The problem also goes away if tBar::PrintDataAndAddress is a non-template function.

For the life of me, I have not been able to find anything in the Standard that explains this behavior. I believe it could be a bad interpretation of 14.6.5 - temp.inject, but I can't claim I have read all of it.

Does anyone know if Clang is right failing to compile the above code? Can you please quote the relevant C++ standard text if that is the case?

Qt Creator Disassembler, what is he trying to tell me?

I have a bug somewhere in the program. I'm using Qt Creator. While debugging, it opens the Disassembler and the cursor goes to the following line:

0x77d50b2d  <+0x3948>        c6 05 85 82 d8 77 00           movb   $0x0,0x77d88285

How should I read this?

I guess Qt Creator is trying to help me but I cannot undertand how to use that information.

How should I use that information?

How to manage lifetime of the type "shortest of"?

We use composition, when an object has a single parent, which should care for the object's lifetime. We use unique_ptr when in the same situation, but the object can be nullptr.

We use shared_ptr when several external entities may need our object, so its lifetime is extended until the last of those external entities loses interest.

Here I want to ask about another lifetime situation. What if the object needs to live the shortest of several durations?

Here is an example. Let's have a one-shot timer, which stores a functor and executes it after a the counting is complete. It makes sense to me*, that this timer object is destroyed after:

1. fulfilling its task - therefore it should be able to destroy istelf

 or

2. the parent loosing interest in the timer - so the parent should be able to 
     destroy the object as well

Currently, I using an awkward implementation with unique pointers. What would be a good pattern / guideline / implementation of this problem?

* reasons: 1) the functor could be owning some other resources 2) the timer could have been set to a very large number, and then abandoned 3) if the parent has been destroyed, we generally don't want to invoke its callbacks

C++11 execute block in same thread but with timeout

Lets say we have block of code, we just cant modify it, but we want to break it, exit this piece of code when it runs too long (x miliseconds)

Pseudo code

Throw exception after (500ms) {
    auto result = Do some risky job, for example test string by regex with catastrophic backtracking risk.
}
catch ( Exception e ) {
    //... 
}

Every thing has to be still in the same thread.

Is it possible with c++11 or with some other standard?

Should I use QScopedPointer or std::unique_ptr?

Should I use QScopedPointer or std::unique_ptr?

I read somewhere that QScopedPointer is not that cool anymore.

Considering I'm starting a project from zero, using Qt5 and QMAKE_CXXFLAGS += -std=c++1y.

C++ upper_bound on struct vector with == operator

I have following struct

struct cube
{
    int  index ,l , b , h;
    bool operator<(const cube & c2) const
    {

    if (l == c2.l && b == c2.b && h == c2.h)
        return index < c2.index;
    if (l == c2.l && b == c2.b)
        return h < c2.h;
    if (l == c2.l )
        return b < c2.b;
    return l < c2.l;
    }
    bool operator==(const cube  c2) 
    {
        return index != c2.index && l == c2.l && b == c2.b;
    }
};

Now I want to apply upper_bound on vector of this struct as per condition in == operator.
However , it is still returning me those iterators where index are same

int pos2 = upper_bound(v.begin(),v.end(),v[i]) - v.begin();

i.e v[i].index is equal to v[pos2].index

Data structure & Algorithms with C++

The easiest way to get the start into Data structure & Algorithms with c++ for my second year at university. and do I need to be really good at c++ before I start doing Algorithms & Structure? Drop your opinions, please.

Why `std::istream_iterator` has not a rvalue constructor?

There is any specific reason that std::istream_iterator cannot receive the stream as an rvalue?

For passing a temporary object, I have to create a function like:

template<class T, class ostream_t>
std::istream_iterator<T> my_it(ostream_t&& ostream)
{ return {ostream}; }

template<class T>
std::istream_iterator<T> my_it() { return {}; }

int main()
{
    std::string file("3.45 1.23 7,56");

    std::copy(my_it<double>(std::istringstream(file)), my_it<double>(),
              std::ostream_iterator(out, " "));
}

However, that would be more convenient, and shorter:

int main()
{
    std::string file("3.45 1.23 7,56");

    using my_it = std::istream_iterator<double>;

    std::copy(my_it(std::istringstream(file)), my_it(),
              std::ostream_iterator(out, " "));
}

Why, after three standard updates (C++11, C++14 and C++17), there is no rvalue constructor for that kind of iterators, when nearly every any other type have it?

You can argue that, since the iterator is copyable and holds a reference, you can get undefined behaviour if the referenced object is no longer alive (std::reference_wrapper has the rvalue construct disabled as well), but that can also happen with lvalue references.

It's an user land responsability after all.

Casting std::tr1::shared_ptr

In my current project we are building for Linux and Windows at the same time. Unfortunately because some platform issues our MSVC is very old. We are using MSVC 2010. And gcc we are using relatively new and smarter which has the version 4.8 .

The code below compile in gcc but MSCV nags about it :

template<class T, class U>
std::shared_ptr<T> Cast( const std::shared_ptr<U>& spObject )   // rename from CastTerrainObject
{
    return std::dynamic_pointer_cast<T>(spObject);
}

template<class T, class U>
std::tr1::shared_ptr<T> Cast( const std::tr1::shared_ptr<U>& spObject ) // rename from CastTerrainObject
{
    return std::tr1::dynamic_pointer_cast<T>(spObject);
}

MSVC began nagging after I add the second overload for std::tr1::shared_ptr. The compile errors I am getting repeatedly :

error C2995: 'std::tr1::shared_ptr<_Ty> Cast(const std::tr1::shared_ptr<_Ty2> &)' : function template has already been defined

And 

 error C2440: 'initializing' : cannot convert from 'std::tr1::shared_ptr<_Ty> (__cdecl *)(const std::tr1::shared_ptr<_Ty2> &)' to 'std::tr1::shared_ptr<_Ty>'

Do you guys have a solution for my case?

Is there a case where ellipsis(vararg) should be preffered over variadic templates

Variadic template have lot of pros, but is there a case when ellipsis(vararg) should be use

C11 for json syntax

I try nlohmann json, it's c11 syntax is really impressive. I want to know how does this works?, and how to implement. please check the below two great features.

using json = nlohmann::json;
json j1 = {
            "pi": 3.141,
            "happy": true,
            "name": "Niels",
            "nothing": null,
            "answer": {
            "everything": 42
             },
            "list": [1, 0, 2],
            "object": {
            "currency": "USD",
            "value": 42.99
           }
         };

     json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;

For boost io_service, is only-one thread blocked on epoll_wait?

I read the source code of Boost ASIO, and I wanna find out it is only one thread for it to call epoll_wait(Of course,if I use epoll reactor). I wanna find its solution about more than one thread to call epoll_wait, this may cause different threads doing the read for the same socket at the same time . I read some key codes as follows:

// Prepare to execute first handler from queue.
      operation* o = op_queue_.front();
      op_queue_.pop();
      bool more_handlers = (!op_queue_.empty());

      if (o == &task_operation_)
      {
        task_interrupted_ = more_handlers;

        if (more_handlers && !one_thread_)
          wakeup_event_.unlock_and_signal_one(lock);
        else
          lock.unlock();

        task_cleanup on_exit = { this, &lock, &this_thread };
        (void)on_exit;

        // Run the task. May throw an exception. Only block if the operation
        // queue is empty and we're not polling, otherwise we want to return
        // as soon as possible.
        task_->run(!more_handlers, this_thread.private_op_queue);
      }

task_ is epoll reactor and it will call epoll_wait in the run, I guess it may only one thread to call it because only one "task_operation_" in the op_queue_, am I right ? If I wanna use epoll in multi-threading, or I may use "EPOLLONESHOT" so that it can ensure that one thread handle one socket at one time. Can anyone help ? please, thanks.

auto vs auto&& for a function return value

Could you tell me please whether I am right that use of auto&& for a function return value is always a better choice than use of auto. For instance, in

auto val = someObj.getVal();

the val will be a copy if getVal() returns a reference. However, use of the universal reference auto&& does not have such a disadvantage? The only information I need to know is whether getVal() is const or not.

Thank you in advance!

dimanche 30 octobre 2016

C++ reinterpret_cast of std::shared_ref to optimize

You have two classes Animal and Dog (where Dog inherits from Animal), and you have a situation where you are often expecting an animal but are sending an instance of a dog. In my particular case, I am often casting a strong pointer (std::shared_ptr<Dog>) to an animal-expecting function (std::shared_ptr<Animal>).

If we accept that we can make the function parameter a reference (std::shared_ptr<Animal>&, avoiding arguments as to why you should not have strong pointers as reference parameters because of concerns of changing ownership with threads), I assume we would be safe memory-wise to cast a std::shared_ptr<Dog> dog using reinterpret_cast<Animal>(dog), right?

And if so, what could come up other than threading issues; such as that of the reference counting variety?

To be clear, the intent is to have a solution that would be used in many instances, where casting once isn't really a viable solution. It's more the issue that there are many objects that would have to be cast.

cutLoadPGMub from Cutil.h - Replacement for Cuda8

I'm trying to read and load an image using cutLoadPGMub method under cutil.h header. But unfortunately i'm using Cuda8 for my development. Having this into account, i found out that cutil.h was last deprecated in Cuda5. Can anyone tell me what is the replacement for cutLoadPGMub method and Cutil.h library for Cuda8?

Thanks.

Scope and assignment to return values

 1 class Foo{
 2 
 3 };
 4 
 5 Foo func1(){
 6   Foo f;
 7   return f;
 8 }
 9 
10 int func2(){
11   int a = 2;
12   return a;
13 }
14 
15 int main(int argc, char** argv){
16   Foo var1;
17   func1() = var1; //OK
18   func2() = 1; //error: expression is not assignable
19   return 0;
20 }

What is the fundamental reason that assignment to the return value that is of built-in type is not allowed but assignment to a return value that is user-defined type is allowed? How is the memory managed that allows one but not the other?

How to prevent thread starvation

I am writing a zero-latency cloud gaming server. It's a software pipeline. In the first stage we capture the screen and in the second stage we encode it to the video.

However after some amount of time the second stage freezes. I tried many platform-indepandent approach, but in vein, either of them will freeze eventually. The answer of How to prevent threads from starvation in C++11 stated that we should use mutex. I tried it. And it can last longer but it still freeze sometimes(rarely). I think mutex is not a explicit hint to prevent thread starvation too. (maybe I am doing wrong?)

Now I use mutex and disable Windows priority boost feature at the same time, but I don't like this solution at all. could anyone provide an example of starvation-free producer and consumer(better in C++11)?

Can std::condition_variables be used as counting semaphores?

This is a follow-up to Can C++11 condition_variables be used to synchronize processes?.

Can std::condition_variable objects be used as counting semaphores?

Methinks not because the object seems bound to a std::mutex, which implies it can only be used as a binary semaphore. I've looked online, including here, here, and here, but can't find reference or example of using these objects as counting semaphores.

C++11 function signature with variadic std::function

I'm trying to implement a function that takes an std::function which returns an it and might get any number of parameter.

I've tried the following but it doesn't compile and I can't understand what the error means.

template <typename ...Args>
void ThrowOnError(std::function<int(Args...)> func, Args... args)
{
    int err = func(args...);
    if (err < 0)
        throw std::exception();
}

int f()
{
    return 42;
}

int f(int x)
{
    return x;
}


int main()
{
    ThrowOnError(f);
    ThrowOnError(f, 1);
}

I tried moving the templated function to header but it didn't work, also if I comment out the f(int x) function and only leave the call with only f , I still get a no matching overloaded function found and 'void ThrowOnError(std::function<int(Args...)>,Args...)': could not deduce template argument for 'std::function<int(Args...)>' from 'int (int)'

What is the problem here? what am I missing in the function? P.S - I would like an answer which takes an std::function if possible, and not add another typename for the functor type.

error: ‘chrono’ is not a namespace-name

I'm try to code a timer which calcule the duration of an algorithm I'm using C++11 with high_resolution_clock, but when I try to compile my code in GCC it shows that error

using namespace std::chrono; error: ‘chrono’ is not a namespace-name

How can I solve this?

Where to put C++ constants? In a separated/shared header (main.h) file?

I use to put constants like:

const QString DATETIME_FORMAT     {"yyyy-MM-dd hh:mm:ss.zzz"};

in a separate file, main.h. Actually I put it on a namespace like:

namespace projectx {
  const QString DATETIME_FORMAT     {"yyyy-MM-dd hh:mm:ss.zzz"};
}

And then, when I want to use DATETIME_FORMAT I have to:

#include "../../main.h"
using namespace projectx;

Depending on where the file using main.h is located the path ../../main.h change. That's a little annoying.

Is this approach standart? What's the alternative?

std::array - 'buffer of size n will be overrun', only in VS

constexpr auto CHUNKS_X = 5, CHUNKS_Y = 5, CHUNKS_Z = 1;
std::array<std::bitset<CHUNKS_X>, CHUNKS_Y> ys;
std::array<decltype(ys), CHUNKS_Z> zs;
if (CHUNKS_Z > 1)
{
    zs[0] = ys;
    //zs.at(1) = ys; //this works
    zs[1] = ys; //this doesn't work
    for (auto &x : zs[1])
    {
        x.flip();
    }
    for (auto z = 2; z < CHUNKS_Z; z++)
    {
        zs[z] = zs[z - 2];
    }
}

The line zs[1] = ys; gives me

error C4789: buffer 'zs' of size 20 bytes will be overrun; 20 bytes will be written starting at offset 20

But only when compiling in VS. Compiling on the command line gives me no such error, nor does using zs.at(1) = ys; instead. Another thing of note is that MSDN says that this should be a warning, not an error.

I realize this might be a subtle compiler flag issue but I haven't the slightest clue where to start looking.

Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x86

Can C++11 condition_variables be used to synchronize processes?

I'm trying to learn about C++11's std::condition_variable. I've read the articles at cppreference.com and cplusplus.com as well as C++0x has no semaphores? How to synchronize threads?.

My question, which I think has not been answered by the three noted articles, is: can "semaphores" that are created with a combination of of std::mutex and std::condition_variable (see the answers to C++0x has no semaphores? How to synchronize threads?) be used to synchronize between processes the way posix named semaphores can be? It's not clear to me that this functionality can be achieved, because I don't see "sharable" information, such as a name, used in the creation of these objects.

detecting user input with QTextEdit (& distinguishing it from application changes)

Gtk3 rich text widget machinery (based upon GtkTextBuffer & GtkTextView) has both "begin-user-action" and "end-user-actions" signals, which permits quickly to process user input conveniently (and distinguish it from application generated changes to the buffer or the view).

But it looks like there is no similar stuff in Qt5. For example, my incomplete understanding is that QTextEdit::insertHtml or QTextDocument::contentsChange or QTextDocument::contentsChanged does not separate changes related to user input (either keyboard, or pasting, etc...) from those done by the application.

What I have in mind is some syntax oriented editor.

I'm probably misunderstanding Qt5 rich text editor support.

(For curious people: I am redesigning & reimplementing my MELT monitor with C & GTK into something with C++11 & Qt5 tentatively called Basixmo; all is GPL free software, but I have not coded yet the Qt5 thing)

Should I use a mutex or a semaphore when making a MOBA game?

I am thinking of making a MOBA game in the future.

I know there is a very probable chance that I will need to make it multi-threaded.

So, should I use a mutex or a semaphore to synchronize it if I make it multi-threaded?

Do I have to delete lambdas?

I am storing pointers to lambdas in dynamically allocated objects:

struct Function {
    SomeType*(*func)(int);
    Function(SomeType*(*new_func)(int)):
        func(new_func) {}
}

Function* myf = new Function(
    [](int x){ return doSomething(x); }
);

delete myf;

Do I have to write something special in the destructor of this class?

Why file is not created in /etc/ directory

Please find the code sample

void createFile(const std::string& FileName, const std::string& Content)
{
    ofstream of(FileName.c_str());
    of<<Content;
    of.close();
}
const std::string testFile = "/etc/testFile";
const std::string EmptyContent = "";
createFile(testFile, EmptyContent);

File is not creating at /etc/ directory. I think this is related to permissions. What extra I have to add in the code to work.

Simple EventHandler/Provider using a variadic template and function pointers

I'm trying to implement an EventProvider/Handler system to facilitate setting up a small application with reactive GUI for a school project. This particular approach to the broader Observer pattern is not mandated, but it seems like the most robust and lightweight - provided it's actually possible.

#pragma once

#include <vector>;
#include <algorithm>;

/// Provides a lightweight interface for implementing event-based behaviour.
template <class ...arg> class EventProvider
{
public:
    /// Defines a pointer to a function equipped to handle an event from this provider.
    typedef void( *EventHandler )(arg... arguments);

    EventProvider();
    virtual ~EventProvider();

    void Subscribe( EventHandler handler );
    void Unsubscibe( EventHandler handler );

    void Notify( arg... arguments );

protected:
    vector<EventHandler> _handlers;
};

template<class ...arg>
EventProvider<...arg>::EventProvider()
{}

template<class ...arg>
EventProvider<...arg>::~EventProvider()
{}

template<class ...arg>
inline void EventProvider<...arg>::Notify( arg... arguments )
{
    for ( auto handler : _handlers )
    {
        handler( arguments );
    }
}

template<class ...arg>
inline void EventProvider<...arg>::Subscribe( EventHandler handler )
{
    if ( find( _handlers.begin(), _handlers.end(), handler ) == _handlers.end() )
    {
        _handlers.push_back( handler );
    }
}

template<class ...arg>
inline void EventProvider<...arg>::Unsubscibe( EventHandler handler )
{
    _handlers.erase( remove( _handlers.begin(), _handlers.end(), handler ),     _handlers.end() );
}

What I have so far builds fine on its own, but if I actually try and include this header and use the code in other places, I get dozens of errors, all of them duplicates of...

C2238 unexpected token(s) preceding ';'

C2143 syntax error: missing ';' before '<'

C4430 missing type specifier - int assumed. Note: C++ does not support default-int

On the line where I've declared my vector of EventHandlers.

C2509 syntax error: '...'

C3211 'EventProvider<>::FunctionName': explicit specialization is using partial specialization syntax, use template <> instead

On all of the function signatures in the implementation following the class template declaration.

C++ approach to configuration

I am implementing a library, and using abstract class which has some different implementations. I want to allow user to select particular implementation using a config file e.g. config.h. I have two questions:

  • How to achieve this without macro ?
  • I am using inheritance to implement the subclasses, is there a way to allow statically compile/link with the chosen class to avoid virtual function lookup and allow other inlining optimization?

I am looking for c++11 solution, but c++14 and c++17 is welcome too.

next iterator after end() in std::list

#include <list>
int main( void )
{
    std::list< int > list0 { 1 , 2 , 3 } ;
    for ( auto current =  std::next( list0.begin() )
        ;      current != std::next( list0.end() )
        ;   ++ current )
    { /*...*/ }
    return 0;
}

does STL guarantee the correctness of current != std::next( list0.end() ) expression.?

Separate implementation and header in c++ class

I created a test class in a test.cpp file and it works well. When I moved all the class from the cpp file to a header (hpp) file my executable did not link (multiple instances of some functions declaration problem).

So having the following class, what can be placed in the header file and what needs to move in my source (cpp) file in order to avoid link errors?

class MyClass {
public:

    MyClass(int record, const std::string& myType, int age, Education* education = 0, int categ = 0, int winningAmount = 0) : record_(record), myType_(myType), age_(age), education_(education), categ_(categ), winningAmount_(winningAmount) {}

    MyClass(const MyClass& rhs) : record_(rhs.record_), myType_(rhs.myType_), age_(rhs.age_),  education_(0), categ_(rhs.categ_), winningAmount_(rhs.winningAmount_)  { 
        education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_); 
    }

    virtual ~MyClass();

    MyClass& operator=(const MyClass& rhs) {
        if (this == &rhs)
            return *this;
        delete education_;

        record_ = rhs.record_;
        myType_ = rhs.myType_;
        age_ = rhs.age_;
        education_ = (rhs.education_ == 0) ? 0 : new Education(*rhs.education_);
    categ_ = rhs.categ_;
    winningAmount_ = rhs.winningAmount_;
        return *this;
    }

    template <typename Appender>
    void Serialize(Appender& appender) const {

        appender.StartObject();

    appender.String("record");
        appender.Int(record_);

        appender.String("myType");
        appender.String(myType_);

    appender.String("age");
        appender.Int(age_);

        appender.String("education");
        if (education_)
            education_->Serialize(appender);
        else
            appender.Null();

        appender.EndObject();
    }

private:

    int record_;
    std::string myType_;
    int age_;
    Education *education_;
    int categ_;
    int winningAmount_;

};

MyClass::~MyClass() {
    delete education_; 
}

strange behavior while using initializer list in c++

I am trying to intialize a vector of strings using initializer list. But I am getting some strange behavior. It works if there are more than one argument in the constructor, but gives an error if that is the only argument. Please see the code below to understand

// option.h file

#ifndef __OPTION_H__
#define __OPTION_H__

#include <string>
#include <vector>

namespace CppOptParser {

    class Option
    {
        std::vector<std::string> names;
        std::string description;
    public:
        // constructors
        Option(const std::vector<std::string>& names);
        Option(const std::vector<std::string>& names, const std::string& description);
        // destructor
        ~Option();
    };
} // namespace CppOptParser

#endif /* __OPTION_H__ */


// option.cpp file

#include "option.h"

namespace CppOptParser {

    Option::Option(const std::vector<std::string>& names)
    {
        this->names = names;
    }

    Option::Option(const std::vector<std::string>& names, const std::string& description)
    {
        this->names = names;
        this->description = description;
    }
    Option::~Option() {}

} // namespace CppOptParser


// main.cpp file

#include "option.h"
#include <iostream>

using namespace CppOptParser;

int main(int argc, char *argv[])
{
    Option *opt = new Option({ "f", "filename"}); // gives error -- error C2440: 'initializing' : cannot convert from 'initializer-list' to 'CppOptParser::Option'
    Option *opt1 = new Option({"f", "filename"}, "output file name"); // works fine
    std::cin.get();
    return 0;
}

I am using visual studio 2013. Please help.

Sum the lowest and highest integer in 2d array

Learning 2d array and and i try to find highest length and lowest length of bricks that possibly can be build. And here's my code:

for(i=0;i<brick;i++){
    for(j=0;j<brick_sides;j++){
        cin>>a[i][j];
    }
}
//Highest and lowest length of each row 
for(i=0;i<brick;i++){
    highest=a[i][0];
    lowest=a[i][0];
    H=0;L=0;
    for(j=0;j<brick_sides;j++){
        if(highest<a[i][j])
        highest=a[i][j];
        if(lowest>a[i][j])
        lowest=a[i][j];
    }
    //display it
    cout << "The highest length in row " << i+1 << "=" << highest << endl;
    cout << "The lowest length in row " << i+1 << "=" << lowest << endl;
    cout << endl;
}

//process to sum the lowest length and highest length that possibly can builded
for(j=0;j<brick_sides;j++){
        H+=highest;
        L+=lowest;
}
cout << L << " " << H<< endl;
return 0;
}

From this code input, it's looks like what i expect

3
1 2 3
4 5 6
7 8 9

But, for the output, there's a problem, it's not like i expected

12 18 // expectation

21 27 // from the code that i build

Is there any 'mistake' in my code that i build?

Convert my J.s code to C++

//Ignore the graphics.My goal is to print the most occurred number,which in this case is 7.

var count = 0;

var num = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

draw = function() {

if (count < 1000) {

    count ++;

    for (var i = 0; i < 100; i ++) {

        num[floor(random(6) + 1) + floor(random(6) + 1)] ++;

    }

    background(255);
    fill(0);
    for (var i = 2; i < num.length; i ++) {

        rect(25 + i*25, 400 - num[i]/42, 17, num[i]/42);

    }

    for (var i = 2; i < num.length; i ++) {

        text(i + ": " + num[i], 15, i*20 - 15);

    }

} else {

    background(255);
    fill(0);
    for (var i = 2; i < num.length; i ++) {

        rect(25 + i*25, 400 - num[i]/42, 17, num[i]/42);

    }

    for (var i = 2; i < num.length; i ++) {

        text(i + ": " + num[i], 15, i*20 - 15);

    }

}

};

C++: Compiler-specific segmentation fault when storing data from file into array

I am writing a C++ program that takes in number from a file ("input10") of this format:

1    0    12
2    3    24
3    8    9
4    9    2
5    10   3
6    11   4
7    14   8
8    16   10
9    16   3
10   17   12

Each number goes into an array p_data[3] (three numbers to each line).

When running in Visual Studio, there is no error and the correct data is stored in the array. I include the #define _CRT_SECURE_NO_WARNINGS here so that I can use strncpy. I am not sure if strncpy is the source of the issue.

When running with g++ -std=c++11 on a CentOS terminal, I get the following error message:

Segmentation fault (core dumped)

I am finding this issue really difficult to debug. Any thoughts?

#include <iostream>
#include <cstring>
#include <string>
#include <stdlib.h>
#include <fstream>
using namespace std;

void get_processes() {
    string curr_line;
    ifstream infile("input10");
    int p_data[3];
    int p = 0;
    char line[1024];

    while (getline(infile, curr_line)) {
        strncpy(line, curr_line.c_str(), sizeof(line));
        line[sizeof(curr_line) - 1] = 0;

        int p_data_count = 0;
        for (int i = 0; line[i] != '\0'; ++i) {
            if (line[i] != ' ') {
                string num = "";
                while (line[i] != ' ') {
                    num += line[i];
                    ++i;
                }

                if (p_data_count < 3) {
                    p_data[p_data_count] = stoi(num);
                    ++p_data_count;
                }
            }
        }
    }

    infile.close();
}

int main() {
    get_processes();

    return 0;
}

samedi 29 octobre 2016

creating a function that returns a string

i'm trying to create a function that takes in numbers and outputs the number in English. for example if the user entered 5 the function should output "five". here is the code i have so far.

string GetEnglishOnes(int ones) {
switch (ones) {
case 1: onesInEnglish = "one"; break;
case 2: onesInEnglish = "two"; break;
case 3: onesInEnglish = "three"; break;
case 4: onesInEnglish = "four"; break;
case 5: onesInEnglish = "five"; break;
case 6: onesInEnglish = "six"; break;
case 7: onesInEnglish = "seven"; break;
case 8: onesInEnglish = "eight"; break;
case 9: onesInEnglish = "nine"; break;
return onesInEnglish;
}
}  

any help will be appreciated

smart pointer and QThread issue

At some point in my code I have:

QThread* thread = new QThread;
Beacon *beacon = new Beacon(beg, end);
beacon->moveToThread(thread);

And the other day I was reading about this thing called smart pointer. If I understand, it might fit in the peace of code above, I tried:

std::unique_ptr<QThread> thread {new QThread};
std::unique_ptr<Beacon> beacon {new Beacon(beg, end)};
beacon->moveToThread(thread);

This, led to:

error: no viable conversion from 'std::unique_ptr<QThread>' to 'QThread *'
    beacon->moveToThread(thread);

What's wrong?

Seg fault: C++ Quicksort using vectors and iterators

I am trying to implement quicksort using C++ containers and iterators.

I am new to C++ STL.

I am getting a seg fault. For all my C programs I always used valgrind to figure out situations like this but right now its not helping. Any tips/suggestions/solutions will be appreciated.

#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>

using namespace std;

void print(vector<int> A){
    for(vector<int>::iterator i = A.begin(); i != A.end(); i++)
        cout << *i << " ";
    cout<<endl;
}

vector<int>::iterator Partition(vector<int>::iterator l, vector<int>::iterator r){
    int x = *l;
    vector<int>::iterator i = l + 1;
    for(vector<int>::iterator j = l + 1; j <= r; j++){
        if(*j < x){
            iter_swap(j, i);
            i++;
        }
    }
    iter_swap(l, (i - 1));
    return i - 1;
}

void QuickSort(vector<int>::iterator l, vector<int>::iterator r){
    if (distance(l, r) <= 1) return;
    vector<int>::iterator p = Partition(l, r);
    QuickSort(l, p - 1);
    QuickSort(l + distance(l, p), r);
}

int main(int argc, const char * argv[]){
    if (argc != 2){
        cout << "Usage: ./Sort <file_name>" << endl; //<file_name> refers to a file of integers where each line contains a number
        return EXIT_FAILURE;
    }

    ifstream infile(argv[1]);

    vector<int> A;
    int num;
    while(infile >> num){
        A.push_back(num);
    }
    //print(numbers);
    int n = 0;
    print(A);
    QuickSort(A.begin(), A.end());
    print(A);
    //cout << n << endl;
    return EXIT_SUCCESS;
}

Using static class variables without allocationg them

Background

So earlier today I was implementing a thin wrapper to std::ofstream that allowed me to write to .csv files easily. I wanted to override the << operator to write value followed by a comma, and then when the time came for a new line, I would print a backspace character and then a new line. I decided to implement the new line behaviour as a template specialization as follows:

// *this << value; => prints the value to the csv file
// *this << CsvWriter::BREAK; => goes to the next line of the csv file
// Example:
//   CsvWriter csv("test.csv", {"Col 1", "Col 2", "Col 3"});
//   csv << "Value 1" << 2 << 3.25 << CsvWriter::BREAK;
class CsvWriter {
 public:
  CsvWriter(const char *fname, std::vector<const char *> headers);
  CsvWriter() = delete;
  CsvWriter(const CsvWriter &) = delete;
  CsvWriter &operator=(const CsvWriter &) = delete;
  ~CsvWriter() = default;

  // Used for the template specialization below
  static struct LineBreak {} BREAK;

  template <typename T>
  CsvWriter &operator<<(T t);

 private:
  std::ofstream out_;
};

template <typename T>
CsvWriter &CsvWriter::operator<<(T t) {
  out_ << t << ',';
  return *this;
}

// This is the specialization for newlines.
// If anything of type LineBreak is passed to this function, this executes.
// *I know \b doesn't work in all cases, but it works on the only
//  system where this will run so... :P*
template <>
CsvWriter &CsvWriter::operator<<(LineBreak) {
  out_ << '\b' << std::endl;  // Remove last comma
  return *this;
}

// The constructor gives an example use of the template specialization
CsvWriter::CsvWriter(const char *fname, std::vector<const char *> headers)
    : out_(fname) {
  for (const char *header : headers) {
    *this << header;  // Prints each string in header
  }
  *this << BREAK;  // Goes to the next line of the csv
}

Brief Explanation

This code works perfectly as is, and compiles with no complaints in gcc. However, I noticed that I was technically not allocating memory to the value BREAK. So to check it out, I tried printing the value of &CsvWriter::BREAK and ran into a linking error (which makes sense, I'm asking for the address of something that's not in memory). And furthermore, if I add the line CsvWriter::LineBreak CsvWriter::BREAK; after the class definition, then I can print the value of &CsvWriter::BREAK no problem (which also makes sense because now I've given it memory.

From this, I can puzzle together that if the value is never used in any compilation unit, the linker will never look for the value and never complain about it. But if I use it (such as grabbing the address), the linker will try and link the name, and not find anything.

Question

While I find this result very useful for what I'm trying to do, I'm curious, is this technically against the C++11 standard? Or is this perfectly valid code? If not, is there a better way to do this with a similarly clear and simple interface?

Removing all nodes with certain value inside doubly linked list

I'm trying to implement a doubly linked list method to remove all nodes with certain value.

This is the code that I have:

void remove(const Object & x) {
        Node* current = head;
        while (current->next != nullptr) {
            if (current == head && current->data == x) {
                Node* victim = current;
                victim->next->prev = nullptr;
                current = current->next;
                delete victim;
            } else if (current->data == x) {
                Node* victim = current;
                Node* prevNode = current->prev;
                Node* nextNode = current->next;
                prevNode->next = nextNode;
                nextNode->prev = prevNode;
                current = current->next;
                delete victim;
            } else {
                current = current->next;
            }
        }
    }

I think that head doesn't point to anything now? And I'm not sure where to go from here

How to initialize a const string as the concatenation of two strings during compilation time?

The following code initializes two const strings during compilation time:

class Test
{
public:
    static constexpr const char* LOS = "Los ";
    static constexpr const char* ANGELES = "Angeles";
};

How to create another constant string (const char* or const std::string) as the concatenation of the two constant strings? Adding the following line

static constexpr const std::string LOS_ANGELES = std::string(LOS).append(ANGELES);

emits the error:

error: the type ‘const string {aka const std::basic_string<char>}’ of constexpr variable ‘Test::LOS_ANGELES’ is not literal

Getting around copy semantics in C++

Please consider this code:

class A
{

};

int main()
{
    std::vector<A> test;
    test.push_back(A());
}

The constructor and destructor will be called twice, also memory will be allocated twice and the object will copied, now not only is that potentially bad for performance it could also lead to run time errors, especially if there's some cleanup going on in the destructor. The way i'd usually get around this is to just create a vector of pointers instead :

std::vector<A*> test;
test.push_back(new A());

My question is two fold, is this common practice and is it good practice? Or is there a better way? If this turns out to be a dupe please let me know and i'll close the question, but I couldn't find anything on searching.

How to know when there is input through the terminal pipe line on C++ 11?

How to know when there is input through the terminal pipe line on C++ 11?

I may call my program like this:

  1. ./main.o solved.txt
  2. cat unsolved.txt | ./main.o
  3. cat unsolved.txt | ./main.o solved.txt

I am using this to know whether I need to read data from the pipe line or not on C++ POSIX Standard:

// If it is passed input through the terminal pipe line, get it.
if( !isatty( fileno( stdin ) ) )
{
    // Converts the std::fstream "std::cin" to std::stringstream which natively supports
    // conversion to string.
    inputedPipeLineString << std::cin.rdbuf();

    printf( "inputedPipeLineString: %s", inputedPipeLineString.str() );
}

But now I want to use the C++ 11 Standard, and my loved fileno and isatty are out of it. So there is an alternative to them on the C++ 11?

std::forward and ref-qualifiers for member functions

I was in a position where I was using std::forward wherever I had a forwarding reference and I was wondering if some of that was unnecessary or even wrong. For example having std::forward in a std::begin() call.

Because of the ability of a class being able to overload its member functions based on whether the call is made with the object as an rvalue or not http://ift.tt/1jM7Wvb, I assumed that a templated function would be as efficient as possible if you were knew that the inner function you were forwarding the object to was non-mutating and/or was a member function of the object. For example

template <typename Something>
void do_something(Something&& something) {
    std::forward<Something>(something).do_something();
    auto iter = std::begin(std::forward<Something>(something));
    for_each(iter, std::end(std::forward<Something>(something), []() {});
}

I saw this question (When not to use std::forward with r-values?) but it did not address the member function ref-qualifiers and it also did not clearly address what the best practice is when you don't have access to the inner functions definitions that you are calling.

Is there a general guideline for when not to use std::forward that addresses the things I mentioned? Or is there some key concept that I am missing?

Understanding of function pointer syntax in c++

I have two questions

  1. Are both of these declarations of setEvalFunction equivalent for using EvalFunctionPtr = T (*)(const std::vector<T>&);?

    a) void setEvalFunction(const EvalFunctionPtr& evalFunc);
    
    b) void setEvalFunction(T (* const &evalFunc)(const std::vector<T>&));
    
    
  2. What is the difference between the following parameters (since both seem to work fine).

    a) T (* const &evalFunc)(const std::vector<T>&)
    
    b) T (* const &evalFunc)(const std::vector<T>&)&
    
    

I want to have something equivalent to 1 a), i.e. passing a reference to a constant function pointer, but without using some extra definition like using EvalFunctionPtr = ....

Why won't my test statement check a *& struct argument accurately?

I've been trying to map out a binary search tree in C++, but I'm having some difficulty with my remove method. If it worked, it would basically use an inorder traversal to search the tree for a node with the value passed into the method, recursively calling itself so long as it's actually on a node that exists - if it's not, then it promptly returns itself and allows the method that's one "step up" in the recursion to check the area it's in, just like a normal inorder traversal. The problem is, my if statement checking to see if the current node exists seems to just not work, always returning true and causing it to infinitely iterate down the left branch that has a reasonable endpoint. Here's the code I'm using:

template<class T>
void binSTree<T>::remove(Node<T>*& nowOn, const T& input)
{
    if(nowOn) //This is the part that breaks. My cout statement has proved that by repeating itself an infinite number of times.
    {
        cout << "So we know it's entering this.";
        if(nowOn->left)
            remove(nowOn->left, input);
        if(nowOn->data == input)
        {
            if(!(nowOn->left) && !(nowOn->right))
            {
                delete nowOn;
            }
            if(nowOn->left && !(nowOn->right))
            {
                if(!(pred(nowOn)->left->data == input))
                    pred(nowOn)->left = nowOn->left;
                else if(!(pred(nowOn)->right->data == input))
                    pred(nowOn)->right = nowOn->left;

                delete nowOn;
        }
        if(nowOn->right && !(nowOn->left))
        {
            if(!(pred(nowOn)->left->data == input))
                pred(nowOn)->left = nowOn->right;
            else if(!(pred(nowOn)->right->data == input))
                pred(nowOn)->right = nowOn->right;

            delete nowOn;
        }
        if(nowOn->left && nowOn->right)
        {
            if(!(pred(nowOn)->left->data == input))
                pred(nowOn)->left = nowOn->right;
            else if(!(pred(nowOn)->right->data == input))
                pred(nowOn)->right = nowOn->right;

            delete nowOn;
        }
    }
    if(nowOn->right)
        remove(nowOn->right, input);
}
else
{
    return;
}
return;
}

The pred method is a simple, non-recursive stack that runs through the entire tree to find something where either the left or right nodes are the input node. That's been tested and works just fine. As for the node, here's the code for it:

template < class T > class binTree;  // forward declaration
template < class T > class binSTree; // forward declaration

template < class T > class Node {
friend class binTree < T >;          // binTree is friend
friend class binSTree < T >;         // binSTree is friend
public:
    // default constructor
    Node ( const T& x = T ( ), Node < T >* l = 0, Node < T >* r = 0 ) :
        data ( x ), left ( l ), right ( r ) { }
private:
    T data;                         // data component
    Node < T > *left, *right;       // left and right links
};

binTree is a different binary tree that can't delete, but has its own insert, height, size, and inorder traversal methods. binSTree, the class with the remove method, is a derived class of binTree. I'm reasonably certain that the error comes from me trying to check a Node<T>*&, the *& part specifically, with an if statement, but I can't figure out how to do anything about it. Anyone have any ideas?

Why does the following C++11 code fails?

The following code (under Visual Studio 2013) fails in the assert. Can someone explain why this happens?

#include <thread>
#include <cassert>

std::thread t;

void threadTask()
{
   assert(t.get_id() == std::this_thread::get_id());
}

int main()
{
    for (int i = 0; i < 1000; ++i)
    {
        t = std::thread(threadTask);
        t.join();
    }
}

I'm looking for a way to check that a function is called from a specified thread...

friend template struct declaration with overloads

Considering the following snippet:

namespace nr {

  template <class ...> using void_t = void;

  template <typename T, typename = void> struct type_id {
    static int const value = 0;
  };
  template <typename T> struct type_id<T, void_t<decltype(T::type_id)>> {
    static int const value = T::type_id;
  };

}

Now I want to make the overload be able to access a private type_id static field. I can not find the correct syntax or whether it is even possible. My attempt below gives 0 instead of the exected 1. You do get 1 if you declare the type_id = 1 member public.

class Foo {
  template <typename T, typename> friend struct nr::type_id;
  static const int type_id = 1;
};

int main() {
  std::cout << nr::type_id<Foo>::value << std::endl;
}

Is this possible, and if so, how?

What all should I know about std::unique_lock?

From what I have understood, std::unique_lock is a kind of wrapper around the underlying mutex object so as to provide a safer implementation over using raw mutexes (e.g., end up in unlocked state if an exception is thrown or on destruction). Is this all std::unique_lock is for?

Try #1

std::mutex m;  // global 
void foo() {
  m.lock();
  // critical section
  m.unlock();
}

Try #2

std::mutex m;  // global 
void foo() {
  std::unique_lock<std::mutex> ul(m);
  // critical section
}

Is Try #2 preferred over Try #1, and is this what std::unique_lock is for? Please provide some other examples where std::unique_lock may be desired.

Strange Behavior of G++ in Ubuntu 14.04.5

recently I'm trying to use Apache Ant with g++4.8 with -std=c++11.

If I tried this code it passed.

#include <cmath>
...
sqrtf((float)100);

However, if I type

#include <cmath>
...
sqrt((float)100);

The g++ compiler will produce the error,

/usr/bin/ld: test.o: undefined reference to symbol 'sqrtf@@GLIBC_2.2.5'
//lib/x86_64-linux-gnu/libm.so.6: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status

Adding -lm doesn't help either. Any ideas?

Thanks!

Linked list deep copy constructor

I am implementing a linked list class' copy constructor which will make a deep copy. This is the code that i have:

List( const List & rhs ) {
        Node* rhsFront = rhs.header->next;
        Node* prev = header;
        while (rhsFront) {
            prev->next = new Node(rhsFront->data, nullptr);
            rhsFront = rhsFront->next;
            prev = prev->next;
        }
}

However, it crashes at this line:

prev->next = new Node(rhsFront->data, nullptr);

What did I do wrong?

Comparing unordered_map vs unordered_set

First of all, what is the main difference between them?

The only thing i've found is that unordered_set has no operator []. How should i access an element in unordered_set, since there is no []?

Which container is using random access to memory(or both)?

And which one of them faster in any sense or using less memory?

can i show a child QWidget on Parental QWidget without layout

/* Qt Code Example for embedding a child in parent and showing it as an Overlay without using a Layout */

    #include "widget.h"
    #include <QApplication>

    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        Widget w; // parent
        w.setStyleSheet("background-color:blue");

        Widget w1; // child Widget w1(&w),
        w1.setParent(&w);
        w1.setStyleSheet("background-color:red");
        w1.setGeometry(400,300,100,100); // i tried many other options as well 
        w1.show();
        w1.setVisible(true);    
        w.show();    
        return a.exec();
    }



I can only see the blue background of parent .
Red Child is  nowhere seen.

Binding const references to const values only

I am working on a code that finds pairs (using a specific condition) among the elements of a collection. I don't really want to duplicate the elements of the collection, so I figured I would use pointer pairs. This however is unsafe if the values in the original collection can change.

In my code I would like to use a const reference that only binds to truly constant values (because I don't want to let the users to abuse the pairs). This approach however:

using PairCollectionType =
    std::vector<std::pair<std::shared_ptr<Cluster>, std::shared_ptr<Cluster>>>;

PairCollectionType getClusterPairCollection(
    const std::vector<Cluster> const& clusterCollection)
{
    // ...
}

-> results an error of "duplicate 'const'". I know that this is possible with pointers:

const ptr_type* const ptrThatBindsOnlyToConsts;

Is this somehow possible with references too?

mutex locking order c++11

I have a (fairly easy) question about std::mutex in c++11:

Suppose 6 threads want to lock the same mutex using std::lock_guard. Thread 1 ask for the lock, after which, thread 2 does the same, etc, until all 6 of them asked for the lock. The first thread to get the lock will make the 5 other threads block until the lock is available for each of them.

Now does the 5 other threads will be receiving the lock in the order they asked for it? Even though they all asked for it, can we take for granted that thread 2 will be the next one to receive the lock, or one of the thread may starve?

Is there a better method than using Map?

I am creating a genetic algorithm that classifies set of data for which I need to generate random sequences of 1s,0s and 2s for defining a rule 2 represents it being in 2 states a 1 and 0. I am trying to use Map STL for mapping the random set of rules generated and the output for each rule. I need the Map key to be dynamic/ changing ever iteration to be filled by new population of rules.

I realise I have option of using pointers which complicates my code and will have readability issue.

The other option I know about is copy the key element and deleting it so it can be replace by the new rule.

So, My question is:

1). Is it better to use vector and my own mapping algorithm? The only problem being is I want to be efficient and fast as I will be dealing with 2000 or more data.

2). Are there any other STL which I can use no libraries that I need to download pls.?

3). Shall I just use Map and keep reseting the elements in the map each time so I can initialise them again?

which method would be effective?

Open to any other suggestion or advice.

no match for ‘operator[]' when trying to simplify code into range-based for-loop for move semantics

I'm trying to reduce and simplify the size of my code, but encountered this error:

BucketSort.cpp: In member function ‘void BucketSort::sort(unsigned int)’:
BucketSort.cpp:118:34: error: no match for ‘operator[]’ (operand types are ‘std::vector<unsigned int> [10]’ and ‘std::vector<unsigned int>’)
         std::move(std::begin(vecs[i]), std::end(vecs[i]), std::back_inserter(numbersToSort));
                                  ^
BucketSort.cpp:118:53: error: no match for ‘operator[]’ (operand types are ‘std::vector<unsigned int> [10]’ and ‘std::vector<unsigned int>’)
         std::move(std::begin(vecs[i]), std::end(vecs[i]), std::back_inserter(numbersToSort));
                                                     ^
make: *** [BucketSort.o] Error 1
Ivans-MacBook-Pro:CS6771A5-ParallelBucketSort ivanteong$

I'm trying to simplify from:

numbersToSort = std::move(vecs[0]); // bucket containing 0 (handle case where there is a number that is 0)
    std::move(std::begin(vecs[1]), std::end(vecs[1]), std::back_inserter(numbersToSort));
    std::move(std::begin(vecs[2]), std::end(vecs[2]), std::back_inserter(numbersToSort));
    std::move(std::begin(vecs[3]), std::end(vecs[3]), std::back_inserter(numbersToSort));
    std::move(std::begin(vecs[4]), std::end(vecs[4]), std::back_inserter(numbersToSort));
    std::move(std::begin(vecs[5]), std::end(vecs[5]), std::back_inserter(numbersToSort));
    std::move(std::begin(vecs[6]), std::end(vecs[6]), std::back_inserter(numbersToSort));
    std::move(std::begin(vecs[7]), std::end(vecs[7]), std::back_inserter(numbersToSort));
    std::move(std::begin(vecs[8]), std::end(vecs[8]), std::back_inserter(numbersToSort));
    std::move(std::begin(vecs[9]), std::end(vecs[9]), std::back_inserter(numbersToSort));

to a range-based for-loop:

for (auto i : vecs) {
    std::move(
        std::begin(vecs[i]),
        std::end(vecs[i]),
        std::back_inserter(numbersToSort)
    );
}

Declarations in my .h file are:

std::vector<unsigned int> numbersToSort;
std::vector<unsigned int> vecs[10] = {
    std::vector<unsigned int>(),
    std::vector<unsigned int>(),
    std::vector<unsigned int>(),
    std::vector<unsigned int>(),
    std::vector<unsigned int>(),
    std::vector<unsigned int>(),
    std::vector<unsigned int>(),
    std::vector<unsigned int>(),
    std::vector<unsigned int>(),
    std::vector<unsigned int>()
};

Does anyone know what is wrong?

Elaborated type specifier in type alias

Why there is no hard error in the following code? Type alias and name of class are exactly the same (compiler clang):

using S = struct S;

struct S {};

S s;

int main()
{
}

Wich name exactly used in the definition of variable in the following code (symbol or type alias)?

using S = struct S {};

int main()
{
    S s;
}

undefined reference to c++ error

Hi guyys i need your help! When i compile run time error is :

/tmp/ccSOgpjn.o: In function Collection::evaluate()': fitnessTest.cpp:(.text._ZN10Collection8evaluateEv[_ZN10Collection8evaluateEv]+0x45): undefined reference tofitnessFunction::doEvaluation(std::__cxx11::basic_string, std::allocator >)' /tmp/ccSOgpjn.o: In function Collection::writeIndividual(char**, int)': fitnessTest.cpp:(.text._ZN10Collection15writeIndividualEPPci[_ZN10Collection15writeIndividualEPPci]+0x3a): undefined reference toreadIndividual::read[abi:cxx11](char**, int)' collect2: error: ld returned 1 exit status

I can not understand why?

my code is :

class fitnessFunction
{
public:
    virtual int doEvaluation(string x);

};

class OneMax: public fitnessFunction
{
public:
    virtual int doEvaluation(string x) {
            int count = 0;
for (int i = 0; i < x.size(); i++)
        if (x[i] == '1') count = count + 1;
        return count;
        }

};

   class readIndividual
     {
       public:
        string read(char * argv[], int i);

      };

   class OneMaxIndividual: public readIndividual
 {
   public:
     virtual string read(char * argv[], int i) {
        string inputFile = argv[i+1];
        ifstream input(inputFile.c_str());
        string x;
        input >> x;
        input.close();
        return x;
    }

};

  class Collection
    {
     public:
     fitnessFunction* m_function;
     readIndividual* m_individual;
     string individual;
public:
    Collection(){}
    void set_function(fitnessFunction* s){
        m_function = s;
    }
    void set_individual(readIndividual* s){
        m_individual = s;
    }
    int evaluate() {
        m_function->doEvaluation(individual);
    }
    void writeIndividual(char* argv[], int i) {

        individual = m_individual->read(argv,i);
    }

};

    int main(int argc, char* argv[])
   {

   int result = 0;
   string outputFile = "fitness.out";
   ofstream output( outputFile.c_str() );

   OneMax fitnessFunction;
   OneMaxIndividual individualObj;

   Collection collection;
   collection.set_function(&fitnessFunction);
   collection.set_individual(&individualObj);

  for(int i = 0; i < argc/2; i++){
     //lettura individo
     collection.writeIndividual(argv,i);
     result = collection.evaluate();
     output << result << endl;
  }

  for(int i = argc/2; i < argc-1; i++){


    collection.writeIndividual(argv,i);
    result = collection.evaluate();
    output << result << endl;

    }

  output.close();

    return 0;
}

I tried a few more questions like mine but have not found answers that I have solved the problem. The above code in all in a one page.

Unexpectedly able to call virtual function from base class ctor

Can anyone help explain this unexpected behavior?

The Premise

I've created class Thread that contains a member std::thread variable. Thread's ctor constructs the member std::thread providing a pointer to a static function that calls a pure virtual function (to be implemented by base classes).

The Code

#include <iostream>
#include <thread>
#include <chrono>

namespace
{

class Thread
{
public:
    Thread()
        : mThread(ThreadStart, this)
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl; // This line commented later in the question.
    }

    virtual ~Thread() { }

    static void ThreadStart(void* pObj)
    {
        ((Thread*)pObj)->Run();
    }

    void join()
    {
        mThread.join();
    }

    virtual void Run() = 0;

protected:
    std::thread mThread;
};

class Verbose
{
public:
    Verbose(int i) { std::cout << __PRETTY_FUNCTION__ << ": " << i << std::endl; }
    ~Verbose() { }
};

class A : public Thread
{
public:
    A(int i)
        : Thread()
        , mV(i)
    { }

    virtual ~A() { }

    virtual void Run()
    {
        for (unsigned i = 0; i < 5; ++i)
        {
            std::cout << __PRETTY_FUNCTION__ << ": " << i << std::endl;
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }

protected:
    Verbose mV;
};

}

int main(int argc, char* argv[])
{
    A a(42);
    a.join();

    return 0;
}

The Problem

As you may have already noticed, there's a subtle bug here: Thread::ThreadStart(...) is called from the Thread ctor context, therefore calling a pure/virtual function will not call the derived class' implementation. This is borne out by the runtime error:

pure virtual method called
terminate called without an active exception
Aborted

However, there is unexpected runtime behavior if I remove the call to std::cout in the Thread ctor:

virtual void {anonymous}::A::Run(){anonymous}::Verbose::Verbose(int): : 042

virtual void {anonymous}::A::Run(): 1
virtual void {anonymous}::A::Run(): 2
virtual void {anonymous}::A::Run(): 3
virtual void {anonymous}::A::Run(): 4

I.e. removing the call to std::cout in the Thread ctor seems to have the effect of being able to call a derived class' pure/virtual function from the base class` constructor context! This doesn't align with prior learning and experience.

Build environment in Cygwin x64 on Windows 10. gcc version is:

g++ (GCC) 5.4.0
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

I'm baffled by this observation and am burning with curiosity about what's going on. Can anyone shed light?

Object do not have a fields that have been set into the overriden operator new without define constructor into the derived class

I have a problem with undersending how work override operator new. I have the base class Task with a overridden operator new:

void* operator new(size_t bytes, const allocate_continuation_proxy& p);

This operator is used for allocate a new task and set private fields from current working task. allocate_continuation_proxy& is refer to current task.

class allocate_continuation_proxy; 

class Task { 
public: 
    virtual ~Task() { 
    } 

    void* operator new(size_t size) { 
        return ::operator new(size); 
    } 

    void* operator new(size_t bytes, const allocate_continuation_proxy& p); 

    allocate_continuation_proxy& allocate_continuation() { 
        return *reinterpret_cast<allocate_continuation_proxy*>(this); 
    } 

    virtual Task* Compute() = 0; 

    inline Task* Continuation() { 
        return _continuation; 
    } 

    inline void Continuation(Task& task) { 
        _continuation = &task; 
    } 

    inline void ContinuationAsNull() { 
        _continuation = nullptr; 
    } 

protected: 
    Task() { 
    } 

private: 
    Task* _continuation; 
    Ct* _cancellationToken; 
}; 

class allocate_continuation_proxy { 
public: 
    Task& allocate(size_t size) const; 
}; 

inline Task& allocate_continuation_proxy::allocate(size_t size) const { 
    Task& t = *((Task*)this); 
    Task* c = (Task*) ::operator new(size); 
    c->CancellationToken(nullptr); 
    c->Continuation(*t.Continuation()); 
    c->PendingCount(0); 
    t.ContinuationAsNull(); 
    return *c; 
} 

inline void* Task::operator new(size_t bytes, const allocate_continuation_proxy& p) { 
    return &p.allocate(bytes); 
} 

I try to execute this code:

class C0 : public Task { 
public: 
    //C0() { 
    //} 

    Task* Compute() override { 
        std::cout « "C0 is computing..." « std::endl; 
        Task* c = Continuation() 
        c->Compute(); //if constuctor C0() is not been to define, this line throw exception because "c" = nullptr, but "c" has to point on instance of C2
        return nullptr; 
    } 
}; 

class C2 : public Task { 
public: 
    Task* Compute() override { 
        std::cout « "C2 is computing..." « std::endl; 
        return nullptr; 
    } 
}; 

class C1 : public Parallel::Task { 
public: 
    Task* Compute() override { 
        std::cout « "C1 is computing..." « std::endl; 
        C0& c = *new (allocate_continuation()) C0(); 
        c.Compute(); 
        return nullptr; 
    } 
}; 

int main() { 
    C1& c1 = *new C1(); 
    c1.Continuation(*new C2()); 
    c1.Compute(); 
    return 0; 
} 

My problem is into the this line:

C0& c = *new (allocate_continuation()) C0(); 

If constuctor C0() is not been to define, refer "c" does not have _continuation that has been set into the allocate_continuation_proxy::allocate(size_t size). But If I define a constructor into the class C0, refer "c" will have a _continuation. I don`t understand why? And How can I get the correct behavior without defining a constructor into the derived class?

vendredi 28 octobre 2016

c++ how to put a pointer to a pointer in dvc

I'm new to c++ (java programmer) and I am working on a homework assignment for an intro course. The purpose is "Constructors, Dynamic Memory Allocation and Overloading Operators" That being said, I'm really stuck on one of the specifics.

I'm creating 2 classes Color, and ColorBox. It was specified in the instruction that the member variables in ColorBox are int width, int height and Color** data. My understanding is that data holds reference to a 2D array of Color objects...

My question is: How do I set some type of empty or basic value for data in the DVC? And does anybody have a link for a decent write up on this kind of pointer? I've found generic write ups on arrays and pointers but I'm still having trouble wrapping my head around this.

Thanks in advance!

SFML undefined reference to `sf::TcpSocket::TcpSocket()'

I am trying to compile SFML simple code:

#include <iostream>
#include <string>
#include <SFML/System.hpp>
#include <SFML/Network.hpp>

using namespace std;

int main(int argc, char* argv[])
{

    sf::TcpSocket socket;
    sf::Socket::Status status = socket.connect("127.0.0.1", 6000);
    if (status != sf::Socket::Done)
    {
        // error...
    }
    return 0;
}

All libs and dependencies are installed:

sudo apt-get install libsfml-dev
sudo apt-get build-dep libsfml

I am using two methods:

g++ -c main.cpp
g++ -o main main.o -std=c++11 -lsfml-graphics -lsfml-window -lsfml-system

g++ -c main.cpp -I/home/x64joxer/SFML-2.4.0/include
g++ -o main main.o -L/home/x64joxer/SFML-2.4.0/lib -std=c++11 -lsfml-graphics -lsfml-window -lsfml-system

But I still have the same problem:

main.o: In function `main':
main.cpp:(.text+0x27): undefined reference to `sf::TcpSocket::TcpSocket()'
main.cpp:(.text+0x38): undefined reference to `sf::IpAddress::IpAddress(char const*)'
main.cpp:(.text+0x54): undefined reference to `sf::TcpSocket::connect(sf::IpAddress const&, unsigned short, sf::Time)'
main.o: In function `sf::TcpSocket::~TcpSocket()':
main.cpp:(.text._ZN2sf9TcpSocketD2Ev[_ZN2sf9TcpSocketD5Ev]+0x30): undefined reference to `sf::Socket::~Socket()'
main.cpp:(.text._ZN2sf9TcpSocketD2Ev[_ZN2sf9TcpSocketD5Ev]+0x56): undefined reference to `sf::Socket::~Socket()'
main.o:(.rodata._ZTIN2sf9TcpSocketE[_ZTIN2sf9TcpSocketE]+0x10): undefined reference to `typeinfo for sf::Socket'
collect2: error: ld returned 1 exit status

I read many tutorials and topics at the forum but I still do not know how too fix it. My system is Kubntu 15. Can anyone know how to fix it?

C++ - could construction of a non-trivial pointer supplied by an allocator type throw an exception?

This question is not limited to the built-in C++11 pointer types (shared_ptr etc) but includes any custom pointer type that could be potentially defined in C++ and included as part of a standards-compliant allocator.

Could the construction of a non-trivial pointer, such as that supplied by a custom allocator (std::allocator_traits<Alloc>::pointer) throw an exception and if so, why?

Which of poll() and multi-thread with blocking recv() uses less resources?

I am trying to build a simple web server with just c++11 and those socket libraries.

I think there are two options for me: poll() and multi-thread with blocking recv().(Let me know if you know other options)

  1. poll() can be just single thread. But the while loop can be quite messy. But you won't encounter a lot of thread-related problem.
  2. So I tried multi-thread with blocking recv() and set recvtimeo. It looks not bad. But I am just curious will this method cost more resources?

How to implement std::forward_list::front

I am trying to implement std::forward_list, but I'm having trouble implementing front().

I tried doing this:

Object & front( ) {
    return header->next;
}

const Object & front( ) const;

but I'm getting an error non-const lvalue reference to type 'int' cannot bind to a value of unrelated type.

Expression: map/set iterators debug assertion for a map of set

Why does this expression hit the debug assertion "Expression: map/set iterators incompatible" in VS 12 ?

std::map<int, std::set<int>> x = 
{
    { 1, {2,3,4} },
    { 5, {6,7,8} }
};

Comparing 2 std::lists of std::pairs - Keeping Unique and Different elements

I have 2 Lists of Pairs, each having matching pairs, non matching pairs, and unique pairs. I want to keep the unique and non matching pairs.

I made this code, which works great for finding the mismatches, but not the unique:

std::list <std::pair<std::string,std::string>> outputList1;
std::list <std::pair<std::string,std::string>> outputList2;
for (auto x: outputList1){
  for (auto y: outputList2){
  //compare x to y
         if(x.first == y.first)
         {
                   if(x.second != y.second)
                   {
                        //mismatch on the second element
                        //do something with it
                    }


        }

  }
}

This is what I tried to pull in the unique. I tried to check to see if I am at the last element of y, and if so, save that pair to pull out the unique elements, but it is pulling in everything. I tried writing this out on paper, but my head is spinning.

  auto &last = *(--outputList2.end());
  for (auto x: outputList1){
  for (auto& y: outputList2){
  //compare x to y
         if(x.first == y.first)
         {
                   if(x.second != y.second)
                   {
                       //mistmatch found so I save it off somewhere
                    }


        }
        else if(&y == &last)
         {
             //unique item found in list x
         }

  }
}

I also tried this to get the end of y on the else if:

        else if(&y == &*std::prev(std::end(outputList2)))

Can you see what I'm doing wrong?

MPICH issue with explicit instantiation(ignoring extern)

I wrote a simple c++ program using explicit instantiation technique as below:

// foo.hpp
#include <iostream>

struct foo
{
  template <typename Arg>
  static void call(Arg arg)
  {
    std::cout << "foo\n";
  }
};

here I have the explicit instantiation of class foo:

// foo.cc
#include "foo.hpp"
template void foo::call(int);

and in the main file I use the extern keyword to tell the compiler the foo::call is already instantiated, so there is no need to compile it again:

// main.cc
#include <iostream>
#include "foo.hpp"

extern template void foo::call(int);

int main(int argc, char const *argv[])
{
  foo::call(1);

  return 0;
}  

I test the program with g++ and mpic++ using gcc-4.9. For g++ when I pass the foo.o it works fine:

g++ -std=c++11 -c foo.cc
g++ -std=c++11 main.cc foo.o -o main

and when I don't pass the foo.o it complains as expected:

g++ -std=c++11 test_simple.cc -o test_simple 
/tmp/ccclcKnc.o: In function `main':
test_simple.cc:(.text+0x15): undefined reference to `void foo::call<int>      
(int)'
collect2: error: ld returned 1 exit status

but when I compile with mpic++ (MPICH) in both cases(either passing or not passing the foo.o) the program compiles which should complain when the foo.o is not passed.

mpic++ -std=c++11 -c foo.cc
mpic++ -std=c++11 main.cc foo.o -o main

or

mpic++ -std=c++11 main.cc -o main // this line shouldn't compile but it does

I tested the code with OpenMPI and the behavior is same as g++. So the question is why the MPICH ignores the extern and compiles the instantiation again.

Thanks,

no type named ‘pointer’ in struct std::iterator_traits<...>

Here are the fragments of my linked_list template :

template < class T , class Allocator = std::allocator< T > >
class linked_list final
{/*... */
    enum constantness { CONST , MUTABLE } ;
    template< constantness is_const > 
    class iterator_base : public std::iterator< std::bidirectional_iterator_tag , node< T > , std::ptrdiff_t , 
                                typename std::conditional< is_const == MUTABLE , T * , const T * >::type , 
                                typename std::conditional< is_const == MUTABLE , T& , const T& >::type >
    {   /* ... */
        typename std::iterator_traits< iterator_base >::pointer operator -> () const { return &( to_obj_node( current_node_ ) -> object() ) ; }
        typename std::iterator_traits< iterator_base >::reference operator * () const { return to_obj_node( current_node_ ) -> object() ; }
        /* ... */
    } ;

    public :  /* types : */
        /* ... */
        using iterator = iterator_base< MUTABLE > ;
        using const_iterator = iterator_base< CONST > ;     
/* I  */using difference_type = typename std::iterator_traits< iterator >::difference_type ;
/* II */using difference_type = std::ptrdiff_t ; 
        /* ... */
} ;


int main( void )
{
    linked_list< int > list{ 1 , 2 , 5 , 7 , 8 , 4 } ;
    auto it = list.begin() ;
    * it = 9 ;
    return 0 ;
}

When I leave line that's marked first uncommented, the code doesn't compile.

g++5.4 :

list2.cxx:105:66: error: no type named ‘pointer’ in ‘struct std::iterator_traits<linked_list<int>::iterator_base<(linked_list<int, std::allocator<int> >::constantness)1u> >’
          typename std::iterator_traits< iterator_base >::pointer operator -> () const { return &( to_obj_node( current_node_ ) -> object() ) ; }

icpc :

list.cxx(105): error: incomplete type is not allowed typename std::iterator_traits< iterator_base >::pointer operator -> () const { return &( to_obj_node( current_node_ ) -> object() ) ; }

With second line all compiles fine.

How to access members of a class with dynamic names Cocos2d-x C++

I have some numbers in my header that I want to access in the code like this.

int _number0;
int _number1;

Then in implementation

_number0 = 10;
_number1 = 20;

int i;
for(i=0; i<2, i++){
    auto number = _number+i; //This is where I'm lost, how to do the right part right in order to get this int by its name created from a String + an Integer.
    CCLOG("Number: %i", number); //Output Number: 10 // Number: 20
}

Thanks for any guideline. Greetings.

pointer being freed was not allocated, without any new usage

I going through a piece of code here. For testing purposes it shows a window (QWidget) when executed.

When I hit close it returns:

my_object(7082,0x7fff7a538000) malloc: *** error for object 0x7fff5199b9b8: pointer being freed was not allocated

Where my_object is an instance of the class instantiated at a QMainWindow.

There is no new usage in all code I'd wrote. And also no delete call. How is that (pointer being freed) possible? I though not using new explicit I'll be outside the dangerous zone.

bsoncxx::to_json return corrupted string

I'm having difficulties converting a bson document to a json string using bsoncxx. The bsoncxx::to_json function return an "invalid"/corrupted std::string object.. I can't read the character in it, and it crash when the std::string is destructed..

I've rebuild everything: mongoc,libbson, mongocxx, etc...

Here's a sample code :

bsoncxx::builder::basic::document doc{};
doc.append(bsoncxx::builder::basic::kvp("test", 1));
auto string = bsoncxx::to_json(doc);

I can't extract the data from the string, because std::end(string) crash with a "read access violation" when I try to copy the content with std::copy...

Image

I'm using mongodb everywhere in the program and accessing bson document and everything works fine. I tried to call bsoncxx::to_json on an already existing bson document returned by a mongodb query but it had the same behavior...

I'm trying to stream a byte array ( plus, some information like how to decode the byte array ) using boost tcp sockets to a nodejs program so I thought I could simply create a document with a "binary field", convert it to json and stream it over the tcp socket...

Anyone knows how I could do that, either by fixing the bsoncxx::to_json, or by using something else ?

thanks

Getting bad_alloc on specific inputs while using C++ strings

I am trying to create a basic program to implement Hamming code for my networking class

The program runs correctly for most cases but there are some specific cases where it breaks with -1073741819

The program takes a string of '0's and '1's as input

When the input string is of length of the form odd number ^ 2 an error occurs giving -1073741819 std::bad_alloc

All other cases seem to work
example input of 8 works, 10 works but of 9 doesn't work.
Similarly input of length 24 works, 26 works but 25 doesn't

Below is the code
It includes some code which does not give an error and I have marked when the irrelevant part starts.

#include<iostream>
#include<cmath>
#include<vector>

using namespace std;

int main(){

string data;
cout<<"Enter data to send => :\n";
cin>>data;

int len = data.length();
int maxPowerOfTwo = log2(len-1) + 1;
int totalLength = len +  maxPowerOfTwo + 1;

vector< int > toSend;
toSend.reserve(totalLength);
toSend[0] = 0;

int l = 0;
int k = 0;

for(int i=0;i<totalLength+1;i++){
    if(l==i){
        toSend[i] = 0;
        if(l==0){
            l++;
        }
        else{
            l*=2;
        }
    }
    else{
        toSend[i] = data[k]-48;
        k++;
    }
}

int currentPower = 0;
int startPosition = 1;

for(;currentPower<maxPowerOfTwo+1;currentPower++){
    int tempSum = 0;
    int tempCounter = 0;
    for(int currentPosition = startPosition;currentPosition<totalLength+1;){
        tempSum = tempSum + toSend[currentPosition];
        tempCounter++;
        if(tempCounter==startPosition){
            currentPosition += startPosition + 1;
            tempCounter = 0;
        }
        else{
            currentPosition++;
        }
    }
    if(tempSum%2!=0){
        toSend[startPosition] = 1;
    }
    else{
        toSend[startPosition] = 0;
    }
    startPosition*=2;
}
string finaltoSend;

for(int i=1;i<=totalLength;i++){ // MARKED LOOP
    if(toSend[i]==0){
        finaltoSend.push_back('0');
    }
    else{
        finaltoSend.push_back('1');
    }
}

/*
==== NOT RELEVANT ====

cout<<"\nData to send => "<<finaltoSend<<'\n';
string received = finaltoSend;
cout<<"\nEnter data received of length "<<totalLength<<'\n';
cin>>received;
int t_len = received.length();
int t_maxPowerOfTwo = log2(t_len-1);
int t_currentPower = 0;
int t_startPosition = 1;
int errorAt = -1;
for(;t_currentPower<t_maxPowerOfTwo+1;t_currentPower++){
    int tempSum = 0;
    int tempCounter = 0;
    for(int currentPosition = t_startPosition;currentPosition<t_len+1;){
        tempSum = tempSum + received[currentPosition-1] - 48;
        tempCounter++;
        if(tempCounter==t_startPosition){
            currentPosition += t_startPosition + 1;
            tempCounter = 0;
        }
        else{
            currentPosition++;
        }
    }
    if(tempSum%2!=0){
        errorAt+=t_startPosition;
    }
    t_startPosition*=2;
}
if(errorAt == -1){
    cout<<"\nNo error";
}
else{
    errorAt++;
    cout<<"\n\nError at \n\n"<<errorAt;
}

==== END ====
*/

return 0;
}

While debugging I found that the program breaks in the second iteration of the marked loop

I have tried finaltoSend.append("0") and also reserving memory before hand but none of the options work

Any hints would be greatly appreciated

How to 'help' the compiler to deduce function template return type from a template parameter which is a function?

To de-clutter code from strtoxx calls, but still have them inlined, I would like to have a function template like:

template <typename STR_TO_NUM> static auto StrToNum( const string& s ) {
    char* pEnd;
    return STR_TO_NUM( s.c_str(), &pEnd, 10 );
}

And call it like

unsigned long x = StrToNum<strtoul>( "1984" );

However I get 'template argument deduction/substitution failed:' error. I can do:

template <typename T, T (*STR_TO_NUM)(const char *, char **, int)> static T StrToNum( const string& s ) {
    char* pEnd;
    return STR_TO_NUM( s.c_str(), &pEnd, 10 );
}

And specify the return type when calling. But it feels like that is redundant. Is there a way to avoid it?

I tried to 'template typedef' STR_TO_NUM using 'using' in C++11, but couldn't figure out how to do that for function types.

Thanks

How to write a large binary file to a disk

I am writing a program which requires writing a large binary file (about 12 GiB or more) to a disk. I have created a small test program to test this functionality. Although allocating the RAM memory for the buffer is not a problem, my program does not write the data to a file. The file remains empty. Even for 3.72 GiB files.

    //size_t bufferSize=1000; //ok
    //size_t bufferSize=100000000; //ok
    size_t bufferSize=500000000; //fails although it is under 4GiB, which shouldn't cause problem anyways
    double mem=double(bufferSize)*double(sizeof(double))/std::pow(1024.,3.);
    cout<<"Total memory used: "<<mem<<" GiB"<<endl;

    double *buffer=new double[bufferSize];
/* //enable if you want to fill the buffer with random data
    printf("\r[%i \%]",0);

    for (size_t i=0;i<(size_t)bufferSize;i++)
    {
        if ((i+1)%100==0) printf("\r[%i %]",(size_t)(100.*double(i+1)/bufferSize));
        buffer[i]=rand() % 100;
    }
*/
    cout<<endl;

     std::ofstream outfile ("largeStuff.bin",std::ofstream::binary);
     outfile.write ((char*)buffer,((size_t)(bufferSize*double(sizeof(double)))));

     outfile.close();

    delete[] buffer;

code does not compile in g++ while it does in clang++

So I have this really short code:

test.cpp

class Base {
    public:
        Base(int i) {};
};

class Child : public virtual Base {
    using Base::Base;
};

int main(int argc, char * argv[]) {
    auto *child = new Child(1);
    return 0;
};

It compiles well under clang++ (3.8.0):

$ clang++ test.cpp -std=c++11

while it fails under g++ (5.4.0):

$ g++ test.cpp -std=c++11
test.cpp: In function ‘int main(int, char**)’:
test.cpp:14:30: error: use of deleted function ‘Child::Child(int)’
     auto *child = new Child(1);
                              ^
test.cpp:8:17: note: ‘Child::Child(int)’ is implicitly deleted because the default definition would be ill-formed:
     using Base::Base;
                 ^
test.cpp:8:17: error: no matching function for call to ‘Base::Base()’
test.cpp:3:9: note: candidate: Base::Base(int)
         Base(int i) {};
         ^
test.cpp:3:9: note:   candidate expects 1 argument, 0 provided
test.cpp:1:7: note: candidate: constexpr Base::Base(const Base&)
 class Base {
       ^
test.cpp:1:7: note:   candidate expects 1 argument, 0 provided
test.cpp:1:7: note: candidate: constexpr Base::Base(Base&&)
test.cpp:1:7: note:   candidate expects 1 argument, 0 provided

For some reason g++ expects Base class to have the default constructor. Why is that?

Why does std::ios_base::ignore() set the EOF bit?

When I read all data from a stream, but make no attempt to read past its end, the stream's EOF is not set. That's how C++ streams work, right? It's the reason this works:

#include <sstream>
#include <cassert>

char buf[255];

int main()
{
    std::stringstream ss("abcdef");
    ss.read(buf, 6);

    assert(!ss.eof());
    assert(ss.tellg() == 6);
}

However, if instead of read()ing data I ignore() it, EOF is set:

#include <sstream>
#include <cassert>

int main()
{
    std::stringstream ss("abcdef");
    ss.ignore(6);

    assert(!ss.eof());        // <-- FAILS
    assert(ss.tellg() == 6);  // <-- FAILS
}

On GCC 4.8 and GCC trunk (Coliru), this has the unfortunate side-effect of making tellg() return -1, which is annoying for what I'm doing.

Is this standard-mandated? If so, which passage and why? Why would ignore() attempt to read more than I told it to?

I can't find any reason for this behaviour on cppreference's ignore() page.

Is it ever necessary to invoke default ctor in constructor initialization list?

For example, if I have the following:

class Foo;  // has default ctor

class Bar {
 public:
  Bar(Foo* f);
}

class MyClass {
 public:
  MyClass();

 private:
  Foo foo_;
  Bar bar_;
}

MyClass::MyClass() : foo_(), bar_(&foo) {}

This more or less compiles without warnings, see http://ift.tt/2eUOeo1 [slightly modified so Foo is fleshed out].

It also compiles fine without foo_() in the initializer list. But is there ever a case where one would need to invoke the default ctor?

Is thread-safe comparison operator of two std::thread::id?

Is thread-safe comparison operator== of std::thread::id and std::this_thread::get_id() as below?

std::thread::id t_id;
if(t_id == std::this_thread::get_id()) {}


For example, Boost 1.62 uses to compare threads id:

As known pthread_equal() is thread-safe and interlocked_read_acquire() is thread safe.


But how can I compare two std::thread::id without std::mutex in C++11/14?

Can I use for this as below?

std::atomic<std::thread::id> t_id;
if(t_id.load(std::memory_order_acquire) != std::this_thread::get_id())

Result for std::atomic<std::thread::id> t_id;:

Result for both:

t_id.is_lock_free() = true
sizeof(t_id) = 8

  • Windows MSVS2013 (v120):

Result:

t_id.is_lock_free() = true
sizeof(t_id) = 8

  • Windows MSVS2013 (v120):

Result:

t_id.is_lock_free() = true
sizeof(t_id) = 4

Does is_lock_free() = true mean, that (t_id.load(std::memory_order_acquire) != std::this_thread::get_id()) is thread safe and does not use std::mutex?