lundi 30 novembre 2015

Where is this function eat memory

When this function start and MAX_CHAIN_SIZE = 6 or 1 this function must work infinite time, but when it start, memory finished faster then time, for 1.5 second it s flow 64 - 67 mb. Where are I'm loose memory here? And HeshFunction have a distructor.

void FixedSet::Initialize(const vector<int>& numbers) {
    bool chainlong = true;
    int key;
    while (chainlong) {
        chainlong = false;
        srand(time(NULL));
        HeshFunction firstLayer(numbers.size());
        for (vector<int>::const_iterator currentNumber =    numbers.begin();
            currentNumber < numbers.end(); ++currentNumber)
        {
            firstLayer_ = firstLayer;
            heshtable_.resize(numbers.size());
            key = firstLayer_.heshing(*currentNumber);
            heshtable_[key].push_back(currentNumber[0]);
            if (heshtable_[key].size() > MAX_CHAIN_SIZE) {
                chainlong = true;
            }
        }
    }

class HeshFunction {
public:
int a_, b_, p_;
int tablesize_;
HeshFunction() {}
explicit HeshFunction(size_t tablesize);
int heshing(int key);
~HeshFunction(){}; };

Lambda construction performance and static lambda?

Consider the following code:

// Classic version
template <class It>
It f(It first, It last)
{
    using value_type = It::value_type;
    auto lambda = [](value_type x){return x > 10 && x < 100;};
    return std::find_if(first, last, lambda);
}

// Static version
template <class It>
It f(It first, It last)
{
    using value_type = It::value_type;
    static auto lambda = [](value_type x){return x > 10 && x < 100;};
    return std::find_if(first, last, lambda);
}

Is there any performance difference between the two? What's the construction time of a lambda function? Is the static version better in terms of performances because the lambda is constructed only once?

Type cast child to grandparent class

Current code:

class A { 
    // Abstract class
    ... 
};

class B : public A { 
    // Concrete class
    ... 
};

class C : public B { 
    // Concrete class
    ... 
};

class D : public C { 
    // Abstract class
    ... 
};

class E : public A {
    // Concrete class
private:
    std::deque< std::shared_ptr<A> > m_deque;

public:
    E& operator+=( std::shared_ptr<D> temp ) {
        m_deque.push_front( temp );
        ...
    }
    ...
};

When trying to overload the += operator I want to push the parameter temp into the deque m_deque. The problem is that the types don't match up. How do I push temp into the deque m_deque?

I was trying to type cast temp, but I'm not sure how to type cast to a grandparent class.

C++ Std::find() fails over generics

The given Error when I am passing in a type as string from the non generic driver class using C++11 (psuedocode below, can't really provide a compilable small example):

stl_algo.h|135|error: no match for 'operator==' in '__first.std::_List_iterator<_Tp>::operator*<std::pair<std::basic_string<char>, std::basic_string<char> > >() == __val'|

I have a vector of Generic type

template <typename A, typename B>
vector<list<pair<A,B>> > myList;

I am trying to insert/remove elements from this list of pairs and am running into this type of error.

.#include <algorithm>

template <typename A, typename B>
bool addToList(const pair<A,B> &searchPair){

    auto & tempIndexList = myList[0];
    auto itr = std::find(std::begin(tempIndexList),std::end(tempIndexList), searchPair.first);  //Line where error occurs

}

I have tried changing from 'searchPair.first' to just 'searchPair' and it still fails with the same error. I'm thinking it has something to do with the fact that it is const, but I'm not really sure as it doesn't seem like it should be causing an error.

Any help is appreciated, thanks

What do explicitly-defaulted constructors do?

Consider the following:

template <class T>
struct myclass
{
    using value_type = T;
    constexpr myclass() = default;
    constexpr myclass(const myclass& other) = default;
    constexpr myclass(const myclass&& other) = default;
    T value;
};

  • To what constructor bodies these function are equivalent?
  • Does myclass<int> x; initialize the integer at 0?
  • For myclass<std::vector<int>> x; what does the default move constructor do? Does it call the move constructor of the vector?

Function Pointers in C++ Class Files

I've been trying to work with function pointers for quite a bit now, and to no avail. I've been working with a few friends to create a C++ 11 library to make creating ASCII games easier, and I've personally been working on creating a menu class. The beef of the class is complete, but one issue - I can't get the buttons to call functions. I always get the error:

terminate called after throwing an instance of 'std::bad_function_call'
what():  bad_function_call

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Obviously the error lies somewhere in the pointers, but I can't solve it for the life of me. Thanks for the help in advance.

Menu.h

#ifndef MENU_H
#define MENU_H

using namespace std;

#include <functional>
#include <string>
#include <map>

class Menu {
    public:
        int numberOfOptions;
        map<int, string> options;
        int currentSelection;
        string title;

        Menu();
        Menu(int initialNumberOfOptions, map<int, string> initialOptions, int initialSelection);
        void display();
        void waitForInput();
        void attachOptionAction(int option, void (*function)());

    private:
        map<int, void (*std::function<void()>)> optionActions;

        void executeOptionAction(int option);
};

#endif

Menu.cpp

#include "Menu.h"
#include <windows.h>
#include <iostream>
#include <conio.h>

Menu::Menu(int initialNumberOfOptions, map<int, string> initialOptions, int initialSelection) {
    title = "";
    numberOfOptions = initialNumberOfOptions;
    options = initialOptions;
    currentSelection = initialSelection;
}

void Menu::display() {
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {0, 0});
    for(int i = 0; i < 10; i++) {
        cout << "          " << endl;
    }

    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), {0, 0});
    if(title != "") {
        cout << title << endl << endl;  
    }

    for(int i = 0; i < numberOfOptions; i++) {
        if(i == currentSelection - 1) {
            cout << "[ " << options[i] << " ]" << endl;
        } else {
            cout << options[i] << endl;
        }
    }
    waitForInput();
}

void Menu::waitForInput() {
    char input;
    while(!kbhit());
        input = getch();
    if(input == 72 && currentSelection > 1) {
        currentSelection--;
    } else if (input == 80 && currentSelection < numberOfOptions) {
        currentSelection++;
    } else if (input == 13) {
        if(currentSelection == 1) {
            executeOptionAction(1);
        }
        return;
    }

    display();
}

void Menu::attachOptionAction(int option, std::function<void()> function) {
    optionActions[option] = function;
}

void Menu::executeOptionAction(int option) {
    (optionActions[option])();
}

test.cpp

#include "Menu.h"
#include <unistd.h>
#include <iostream>
#include <iomanip>
#include <map>

void test() {
    cout << "Hello, World!";
}

int main() {
    map<int, string> options;
    options[0] = "Play";
    options[1] = "Help";
    options[2] = "Quit";
    Menu menu(3, options, 1);
    menu.title = "ASCII Game Library 2015";
    menu.display();

    void (*actionPointer)() = NULL;
    menu.attachOptionAction(1, (*actionPointer));

    return 0;
}

Which is the correct way to set a build .env

I would like to configure a C/C++ project with some environment variables:

  • Path to the compiler
  • Product to build
  • C/C++ defines
  • ...

I currently have a custom script that I called ./configure which has nothing to do with autotools. I used it like with arguments:

$ cd project
$ ./configure --product=foo --compiler=new

This configure will setup a C header file, and some Makefiles files that will be included with the -include directive.

I've recently found a somehow better solution involving a .env script that needs to be sourced:

$ cd project
$ echo All is done with autoenv

The autoenv script does the trick. Unfortunately I am not sure this way is the correct way to work. Especially that I will need to remove all the environment variables that I put on my $PATH when I leave the project.

What is the common way to deal with that issue?

Some hints about my configuration:

  • Running on Git
  • Using a proprietary compiler
  • Using make and Python

One possible solution that I've come across is to instanciate a new shell with the environnment set on it. A problem may appear if I forgot to exit the environment when I leave the project.

C++11 discarding numbers in a PRNG sequence

I am trying to use the function discard to skip numbers in a sequence of random numbers. Here is my try:

#include <random>
#include <iostream>

using namespace std;

int main ()
{
  unsigned seed = 1;
  uniform_real_distribution<> dis(0,10);
  mt19937 gen (seed);
  cout << dis(gen) << endl;
  //gen.discard(1); // supposed to be the same of `dis(gen)`?
  cout << dis(gen) << endl;
  cout << dis(gen) << endl;
}

The output of this code is

9.97185
9.32557
1.28124

If I uncomment the line with gen.discard(1) I get

9.97185
0.00114381
3.02333

but I was expecting that the first two numbers are 9.97185 and 1.28124, since the number 9.32557 would be skipped.

Q: How to use discard properly or, is there an alternative solution with the same effect I want? I could simply use dis(gen), but maybe it i

Thanks.

Inheriting templated constructor from class template?

What would be the syntax to inherit constructors (some of them are template) from a class template in C++11 ?

template <class T>
struct Base
{
    using type = T;
    explicit constexpr Base(const type& x): value{x} {};
    template <class U> explicit constexpr Base(U&& x): value{std::forward<U>(x)} {};
    type value;
}

struct Derived: Base<bool>
{
    using Base::Base<bool>; // Does not seem to work ?!?
}

initializer_list

Considering the following code snippet...

void boo(std::initializer_list<unsigned> l)
{
}

template <class T>
void foo(std::initializer_list<T> l)
{
    //Even though T is convertable, initializer list is not...:-(
    boo(move(l));
}

int main()
{
    foo({1u,2u,3u}); //Compiles fine as expected
    foo({1,2,3}); //Fails to compile at line 9... - could not convert...
    return 0;
}

... I'm surprised that initializer_list is not convertible to initializer_list, event though int converts to unsigned.

I've been wondering in what way one can write foo to allow the conversion. Can one somehow unwrap the list having the wrong type and recreate a new list with the right type?

C++ literal passed to const reference leads to automatic construction

If I call the "func(const generic& ref)" with an integer as argument (instead of a 'generic' object), the constructor generic(int _a) will be called to create a new object.

class generic
{
    public:
    int a;

    generic() {}

    generic(int _a) : a(_a)
    {
        std::cout << "int constructor was called!";
    }

    generic(const generic& in) : a(in.a)
    {
        std::cout << "copy constructor was called!";
    }
};

void func(const generic& ref)
{
    std::cout << ref.a;
}

int main()
{
    generic g(2);

    func(g); // this is good.

    func(generic(4)); // this is good.

    func(8); // this is good...... ?

    return 0;
}

The last "func(8)" call creates a new object using the constructor generic(int _a). Is there a name for this kind of construction? Shouldn't the programmer explicitly construct an object before passing the argument? Like this:

func(generic(8));

Is there any benefit in passing the integer alone (other than saving time)?

Although unique_ptr guaranteed to store nullptr after move, it still is pointing to the object?

I've tested following code with GCC 5.2 (C++11):

#include <iostream>
#include <memory>

struct Foo
{
    Foo()      { std::cout << "Foo::Foo\n";  }
    ~Foo()     { std::cout << "Foo::~Foo\n"; }
    void bar() { std::cout << "Foo::bar\n";  }
};

void f(const Foo &)
{
    std::cout << "f(const Foo&)\n";
}

int main()
{
    std::unique_ptr<Foo> p1(new Foo);  // p1 owns Foo
    if (p1) p1->bar();

    {
        //p1->bar();
        std::unique_ptr<Foo> p2(std::move(p1));  // now p2 owns Foo
        f(*p2);
        p1->bar();
        if(p1==nullptr)
        {
            std::cout<<"NULL"<<std::endl;
        }
        p1 = std::move(p2);  // ownership returns to p1
        std::unique_ptr<Foo> p3;
        p3->bar();
        std::cout << "destroying p2...\n";
    }

    if (p1) p1->bar();

    // Foo instance is destroyed when p1 goes out of scope
}

So now my question is, although p1 is guaranteed to be nullptr after move operation, it seemed still is pointing to the previous object?

Using new (nullptr) in decltype context

Is it allowed by the Standard to write decltype(::new (nullptr) T(std::declval< Args >()...)) or noexcept(::new (nullptr) T(std::declval< Args >()...))? Particularly interested placement new on nullptr correctness. Considering following code:

#include <type_traits>
#include <utility>

struct S { S(int) { ; } ~S() = delete; };

struct A
{
    template< typename T,
              bool is_noexcept = noexcept(::new (nullptr) S(std::declval< T >())) >
    A(T && x) noexcept(is_noexcept)
        : s(new S(std::forward< T >(x)))
    { ; }

    S * s;
};

static_assert(std::is_constructible< A, int >{});
static_assert(!std::is_constructible< A, void * >{});

Disabler typename = decltype(S(std::declval< T >())) would need presence of destructor, but placement new not.

Nevertheless unevaluated context of decltype and operator noexcept I wondering about conformance to the Standard. Because compiler may prove 100% incorectness of the tested expression.

Strange class error

I just don't understand why I get this error when I compile this single file main.cpp

#include <iostream>
#include <string>

class Hola{
    private:
        std::string saludo;
    public:
        Hola();
        void salut();
};

Hola::Hola(){}

void Hola::salut(){
    std::cout << "El string es " << saludo << std::endl;
}

int main{
    Hola greet;
    greet.salut();
}

And the compiling error when I type g++ -std=c++11 -o main main.cpp in the console is:

main.cpp:19:7: error: expected primary-expression before ‘greet’
  Hola greet;
       ^
main.cpp:19:7: error: expected ‘}’ before ‘greet’
main.cpp:19:7: error: expected ‘,’ or ‘;’ before ‘greet’
main.cpp:20:2: error: ‘greet’ does not name a type
  greet.salut();
  ^
main.cpp:21:1: error: expected declaration before ‘}’ token
 }
 ^

For whoever that asks, I made this simple program because I didn't understand another one much larger and tried to simplify so I get what's wrong.

Initializer list as a variadic template argument

I have a couple of classes A, B, and F, all having different constructor signatures, like these:

class A {
public:
     A() {}
};

class B {
    double x_, y_;
public:
    B(double x, double y) : x_(x), y_(y) {}
};

class F {
    vector<unsigned> factors_;
public:
    F(std::initializer_list<unsigned> factors) : factors_(factors) {}
};

The objects of these classes need to be registered somewhere, so the construction should go through a factory, like this:

template<class R, typename... Args>
inline R & factory(Args &&... args)
{
    R * rp = new R(std::forward<Args>(args)...);
    /* do fancy stuff with rp... */
    return *rp;
}

This works fine for classes A and B, but not for F, because typename... wants to take one or more types:

A & a = factory<A>();   // okay     
B & b = factory<B>(0.707107, 0.707107);  // okay
F & f = factory<F>({2, 3, 5, 7, 11});  // error: no matching function for call to ‘F::F()’ in factory

Question: Is there any way to make it work with the general factory<R>(args...) syntax?

I tried a full specialization of the factory function for <F, std::initializer_list>, but either messed up the syntax or, when it compiled, wasn't picked up as factory by the compiler.

Any other ideas?

Can I automatically deduce child type in base class template method?

For a start, let me provide a bit context. I'm creating a small game framework for my game, where I have gameplay system and event system. I try to use language features such as templates to avoid boilerplate in user code.

There is Component class, from which other game elements are derived, i.e. Camera, Sprite, Button.

using EventType = unsigned int;
using EventCallback = std::function<void(Event)>;

class Component {
public:
    // This is public version for general functor objects,
    // particularly used with lambda
    void addHandler(EventType type, const EventCallback &callback);

protected:
    // Method for child classes. Creates event handler from method of the class.
    //
    // This is template method, because std::bind is used for functor creation,
    // which requires class type at compile time.
    template <class T>
    void addHandler(EventType type, void (T::*method)(Event event)) { /*...*/ }
private:
    // ...
};

Every component listens to particular set of events, so it doesn't have to implement handlers for every possible type of event. Also, component user should be able to add custom event listeners without creating new class for each game element, for example:

class Button : public Component {
public:
    Button() {
        addHandler(kOnTouch, &Button::onTouch);
    }
    // ...
};

Button ok, cancel;
ok.addHandler(kOnClick, [](Event) {
    // ...
});

cancel.addHandler(kOnClick, [](Event) {
    // ...
});

// Add another handler somewhere else in the code
cancel.addHandler(kOnClick, someCallback);

So, what I want to do is late binding, with compile-time check for member functions. I want to ensure that method pointer passed to addHandler() belongs to child class that called addHandler(). I can get type of method owner inside addHandler() with help of template argument deduction. But I didn't find a way to deduce child class type. Here how I tried to accomplish this with decltype(*this) and type traits:

template <class T>
void addHandler(EventType type, void (T::*method)(Event event)) {
    /***** This check is INCORRECT *****/
    // Check that T is same as child class
    using ChildClass = std::remove_reference<decltype(*this)>::type;
    static_assert(std::is_same<T, ChildClass>::value,
                  "Event handler method must belong to caller class");

    using namespace std::placeholders;

    EventHandler::Callback callback =
            std::bind(method, static_cast<T *>(this), _1);
    addHandler(EventHandler(type, callback));
}

Here we need child class type to compare T with. It seems that ChildClass being assigned to base Component class rather than to child. Is there a way to deduce child class type automatically, changing only inside of method-version addHandler()? It's important to template only this overloaded addHandler() and not the whole Component class to minimize generated code and be able to use polymorphism. So it is tiny wrapper around more generic addHandler(), taking std::function.

At the moment, I can only check that T is Component:

static_assert(std::is_base_of<Component, T>::value,
              "Event handler method must belong to caller class");

Unable to print from fstream

I am trying to change a file's open mode from ios::in | ios::out to only ios::out by closing the open file and opening in the new mode. I have stored my fstream inside a class file_handler whose member functions read and write from/to the file. But after opening in the new mode, the functions do not seem to work.Here's my code (adapted from a bigger program for the question here) :

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class file_handler
{
protected:
    fstream file;
    string path;
public:
    void file_open();
    void print();
};

void file_handler::file_open()
{
    cout << "\n ENter filename : ";
    cin >> path;
    file.open(path, ios::out | ios::in);
}

class html : public file_handler
{
    string  title, body;
public:
    void get_data();
    void write_file();
};

void html::get_data()
{
    cout << "\n enter title : ";
    cin >> title;
    cout << "\n enter body : ";
    fflush(stdin);
    cin >> body;
}

void html::write_file()
{
    file.close();
    file.open(path, ios::out);
    file.seekg(0);
    file << "\n title : " << title << "\n body : " << body;
    print();
}

void file_handler::print()
{
    cout << "\n\n Here is your html file";
    string temp;
    while(getline(file, temp))
        cout << temp << endl;
}

int main()
{
    html F;
    F.file_open();
    F.get_data();
    F.write_file();
}

Can you point out the mistake(s) and kindly suggest a solution. Any help would be greatly appreciated.

How to get identical pairs from two vectors in c++

I define two vectors : vector > vec1 & vec2.
I want to find same pairs from vec1 and vec2. For example, vec1 = [(1,2),(1,9), (2,13), (3,5)] vec2 = [(8, 7), (4,2),(2,10) ,(1,9)]. Then the result should be [(1,9)]. Thanks.

std::tuple, get item by inherited type

In c++11 I have very neat and working code for extracting std::tuple item by type (As I know this feature even placed to c++14 stl)

Now I'm facing with the task to select item by the inherited class specification

 struct A
 {
     int a;
 };
 struct B : public A
 {
     int b;
 };

 ...
 auto tval = std::make_tuple(1, B());
 //now I would like to reference items as following:
 tuple_ref_by_inheritance<A>(tval).a = 5; //Access to B instance by parent A

Following code is my unsuccessful try:

    template< class T, class Tuple >
    struct tuple_ref_index;

    // recursive case
    template<class T, class Head, class... Tail >
    struct tuple_ref_index<T, std::tuple<Head, Tail...> >  
    { 
        enum { value = tuple_ref_index<T, std::tuple<Tail...>>::value + 1 };
    };

    template<class T, class Head, class... Tail >
    struct tuple_ref_index<T, std::tuple<Head, Tail...> >  
    { 
        const static typename std::enable_if<
              std::is_same<T, Head>::value>::type* _= nullptr;
        enum { value = 0 };
    };

    template <class T, class Tuple>
    inline T& tuple_ref_by_inheritance(Tuple& tuple)
    {
        return std::get< tuple_ref_index<T, Tuple>::value >(tuple);
    }

How to get part of xml as string

I saw similar questions in other languages but not in QT using c++. I can only get one string which is a xml data. In this string data there are more than one xml. First have instructions for me and the other I should only copy to another file. Like in this example:

<response>
    <path>C:/foo.xml</path>
    <language>en</language>
    <xmlToCopy>
        <someField1>
            <nest1></nest1>
            <next2></next2>
        </someField1>
        <someField2>bar</someField2>
    </xmlToCopy>
</response>

Till now I've been using QString to get substring beggins with "" and end at "" but it's very error prone and slow. Is there other possibilities of getting part of xml between specific fields?

Use of std::move in parameter construction

I'm trying to construct an object from a function and later pass it to a function that uses it (and consumes it). Here's the code

std::unique_ptr<Object> createObject() {
  auto myobj = std::make_unique<Object>();
  .. modify myobj ..
  return std::move(myobj);
}

void consumeObject(Object&& robj) {
  myvector.emplace_back(std::forward<Object>(robj));
}


consumeObject(createObject()); // Is this right?

I'm not using rvalue references directly from the createObject since I would return a reference to deallocated memory.

Is std::move necessary in the part indicated in the code? What happens if, like I did in the code above, I pass a rvalue to be bound to the rvalue reference? The code seems to compile just fine but I can't see the difference between a

consumeObject(createObject());

and

consumeObject(std::move(createObject()));

Double checked locking: Fences and atomics

So I did some reading: http://ift.tt/1H5Y3Fp and http://ift.tt/1t46fiU . I found this code for using it

std::atomic<Singleton*> Singleton::m_instance;
std::mutex Singleton::m_mutex;

Singleton* Singleton::getInstance() {
    Singleton* tmp = m_instance.load(std::memory_order_relaxed);
    std::atomic_thread_fence(std::memory_order_acquire);
    if (tmp == nullptr) {
        std::lock_guard<std::mutex> lock(m_mutex);
        tmp = m_instance.load(std::memory_order_relaxed);
        if (tmp == nullptr) {
            tmp = new Singleton;
            std::atomic_thread_fence(std::memory_order_release);
            m_instance.store(tmp, std::memory_order_relaxed);
        }
    }
    return tmp;
}

and there is one thing that is not clear to me. Does it work differently than following code without fences?

std::atomic<Singleton*> Singleton::m_instance;
std::mutex Singleton::m_mutex;

Singleton* Singleton::getInstance() {
    Singleton* tmp = m_instance.load(std::memory_order_acquire);
    if (tmp == nullptr) {
        std::lock_guard<std::mutex> lock(m_mutex);
        tmp = m_instance.load(std::memory_order_acquire);
        if (tmp == nullptr) {
            tmp = new Singleton;
            m_instance.store(tmp, std::memory_order_release);
        }
    }
    return tmp;
}

What I mean if I replace fences with appropriate memory order in load/store, does it work the same?

Get class name of the caller that calls member function

I have a base class. One of its member function needs the name of the caller's class as one of the template argument. Let's call it "work".

template<typename T>
void work() {
    // ...
}

Then I may use it in this way, assuming that "obj1" and "obj2" are instances that subclasses the base class I just mentioned,

obj1.work<std::remove_reference<decltype(obj1)::type>>();
obj2.work<std::remove_reference<decltype(obj2)::type>>();

The trouble is that each time I need to use std::remove_reference and then decltype, despite that these types can be known before compiling. Can I somehow avoid writing them? Is there some macro that can help "generate" them? Thanks!

Conversion from std::pair

Here's an example that works on C++03 (-std=c++03) but fails on GCC and VS2015 for C++11 (-std=c++11, /Qstd=c++11)

#include <utility>

class B {
public:
   B(float);
};

class A {
public:
   A(B);
};

std::pair<int, A> a(std::make_pair(1, 2.0));

I have no idea why this would be invalid.. as far as I can see, the A members are direct-initialized by float as described in http://ift.tt/1Ijd3FZ . Is there an SFINAE test for implicit convertibility? As far as I can see, on cppreference it doesn't mention anything like that.

Allow const member function to edit some member variable using mutable

I want to apply the Memoization technique to increase performance of a "Line" class which was like this:

class line{
    public:
        line() = default;
        ~line() = default;

        float segment_length() const;

        Tpoint first;
        Tpoint second;
    };

As you see, the member function segment_length is marked as const because it just compute the length and does not affect the class. However, after applying the Memoization, the class line became:

class line{
    public:
        line() = default;
        ~line() = default;

        float segment_length();

        Tpoint first;
        Tpoint second;

    private:
        float norm_of_line_cashed = -1; //for optimization issue
    };

The member functionsegment_length is not const anymore becuase it is alter the norm_of_line_cashed memebnre variable.

The question:

what is the correct manner in this case:

  • Leave segment_length as non-const member function.
  • Make it const again and mark norm_of_line_cashed as mutable.

Observable containers

I often face situations where I need to create a selection from a data source, manipulate the selection and feed the changes back to the original data source. Something like

#include <vector>

void manipulate(std::vector<int> &vector) {
    // Manipulate vector...
}

int main() {
    // Data source
    std::vector<int> dataSource{1, 2, 3, 4};

    // Select every second entry
    std::vector<int> selection{v[0], v[2]};

    // Manipulate selection
    manipulate(selection);

    // Feed data back to the data source
    dataSource[0] = selection[0];
    dataSource[2] = selection[1];

    return 0;
}

In order to automate the process of feeding the data back to the data source, I could change the selection to a vector of pointers or references (using std::reference_wrapper) and pass that to the function which manipulates its argument. Alternatively, I could create a class ObservableVector which holds the data source as a member and propagates all changes made to it to the data source. However, in both cases, I would need to change the signature of manipulate to accept a vector of pointers or an ObservableVector. Is there any chance I can keep the original manipulate function (without the need to create a wrapper function) and still automate the process of feeding the data back to the original source?

Is calling functions from other functions or as a parameter to an array a good/bad practice? [on hold]

Let's say I've objects A and B.

Is it a good practice to call functions/parameters like this:

A[B->getValue()].setValue(C.getValue() + 10);

Consider all the required assumptions like A is an array, B is object pointer, C is an object, setValue and getValue are methods of that class etc.

The only gist of this question is if calling functions like that is good? Or should it be more like:

Temp1 = b->getValue();
Temp2 = c.getValue();
A[Temp1].setValue(Temp2 + 10);

Enumerate all indices of multidimensional array at compile time

I want to generate a bunch of tuples of different combinations of types in generic number of dimensions. Each dimension have its own size. Say, I have a class template:

template< std::size_t i > struct T {};

For 3-dimensional "space" of sizes 5, 3, 2 I want to generate all possible combinations of 3-tuples of types T< I0 >, T< I1 >, T< I2 >, where I0, I1 and I2 are:

0 0 0
0 0 1
0 1 0
0 1 1
0 2 0
0 2 1
1 0 0
1 0 1
1 1 0
1 1 1
1 2 0
1 2 1
....
4 0 0
4 0 1
4 1 0
4 1 1
4 2 0
4 2 1

I wrote the following code:

#include <type_traits>
#include <utility>
#include <iterator>
#include <iostream>
#include <initializer_list>
#include <algorithm>

template< typename F, std::size_t ...indices >
struct enumerator
{
    static constexpr const std::size_t size_ = sizeof...(indices);
    static constexpr const std::size_t count_ = (indices * ...);

    template< typename I >
    struct decomposer;

    template< std::size_t ...I >
    struct decomposer< std::index_sequence< I... > >
    {
        F & f;

        static constexpr const std::size_t indices_[size_] = {indices...};

        static
        constexpr
        std::size_t
        order(std::size_t const i)
        {
            std::size_t o = 1;
            for (std::size_t n = i + 1; n < size_; ++n) {
                o *= indices_[n];
            }
            return o;
        }

        static constexpr std::size_t const orders_[size_] = {order(I)...};

        static
        constexpr
        std::size_t
        digit(std::size_t c, std::size_t const i)
        {
            for (std::size_t n = 0; n < i; ++n) {
                c = c % orders_[n];
            }
            return c / orders_[i];
        }

        template< std::size_t c >
        constexpr
        bool
        call() const
        {
            auto const i = {digit(c, I)...};
            std::copy(std::cbegin(i), std::cend(i), std::ostream_iterator< std::size_t >(std::cout, " "));
            std::cout << std::endl;
            return f.template operator () < digit(c, I)... >(); // error here
        }

    };

    decomposer< std::make_index_sequence< size_ > > decomposer_;

    constexpr
    bool
    operator () () const
    {
        return call(std::make_index_sequence< count_ >{});
    }

    template< std::size_t ...counter >
    constexpr
    bool
    call(std::index_sequence< counter... >) const
    {
        return (decomposer_.template call< counter >() && ...);
    }
};

#include <cstdlib>

struct print
{
    template< typename ...indices >
    constexpr
    bool
    operator () () const
    {
        std::cout << __PRETTY_FUNCTION__ << std::endl;
        return true;
    }
};

int
main()
{
    print const print_{};
    enumerator< print const, 11, 7, 3 >{{print_}}();
    return EXIT_SUCCESS;
}

LIVE EXAMPLE

It works fine except for the expression f.template operator () < index(c, I)... >(), where indices pack index(c, I)... recognized as not constexpr.

Why is it so? I know the workaround using std::index_sequence, but compilation time differs too much.

How to generate desired sequences at compile time?

dimanche 29 novembre 2015

Idiomatic acronym for a smart pointer

When I write WidgetP, everyone understands that I mean a pointer to Widget. I was using WidgetUP for std::unque_ptr<Widget> and WidgetSP for std::shared_ptr<Widget>. This was all good until I needed to give the client of my class a choice of which smart pointer to use:

template<class Widget>
using WidgetUP = std::unique_ptr<Widget>;
template<class Widget>
using WidgetSP = std::shared_ptr<Widget>;
template<class Widget>
using DefaultWidgetSP = WidgetUP<Widget>; // here SP stands for smart pointer, 
                                          // not shared pointer!

template <class Widget, 
          template <class> class WidgetSP_ = DefaultWidgetSP>
struct MyContainer {
    ... 
};

Now the SP acronym is overloaded: at times it stands for smart pointer and at other times it stands for shared pointer? Is there an idiomatic notation for this case?

why this Singleton in c++11 does't work well?

template<typename T>
class Singleton
{
    public:
    Singleton() = default;
    ~Singleton() = default;
    //forbid copy and asign
    Singleton(const Singleton &) = delete;
    Singleton&operator=(const Singleton&) = delete;

    //make singleton instance by args
    template <typename...Args>
    static void makeInstance(Args&&...args)
    {
        std::call_once(flag, make_shared_instance<T>, std::forward<Args>(args)...);
    }

    //get instance
    static std::shared_ptr<T> Instance()
    {
        if (!instance)
        {
            throw std::exception("instance not make!");
        }

        return instance;
    }

private:
    template <typename...Args>
    static void make_shared_instance(Args&&...args)
    {
        instance = std::make_shared<T>(std::forward<Args>(args)...);
    }

    static std::once_flag flag;
    static std::shared_ptr<T> instance;
};

when I use it like this : Singleton::makeInstance(10); which with parameters it works well but
Singleton::makeInstance(); which without parameters it works not well. this is why? should one help me ?

Iterate over tuple without dereferencing elements

I have a std::tuple (or a boost fusion tuple) whose elements cannot be trivially constructed (for example references) and I want to iterate over the types but not the values of the elements.

In this example I have a (general) tuple type and I want to generate a vector with (runtime) type information. The example below works if all the types in the sequence are trivially default constructed but not in general.

In summary, I want a function that transform: std::tuple<...> -> std::vector<std::type_index>

#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/algorithm/iteration/for_each.hpp>
#include <typeindex>
#include<vector>

using tuple_type = std::tuple<std::string&, int>;

int main(){
    std::vector<std::type_index> types;
    boost::fusion::for_each(
        tuple_type{},  // fails because of std::string&
        [&types](auto& e){types.push_back(typeid(e));} 
    ); 
}

The problem is that I have to generate runtime information from non runtime information and I can't figure out how to mix the fusion functions (http://ift.tt/1Op9aAy) and the metafunctions (http://ift.tt/1XCa6Cc).

I tried with boost::fusion::accumulate and boost::fold but the situation is always the same, at some point I have to generate a runtime element in order to apply the algorithm.

i got error C2027 and error C2227

There are some errors in functions Call::NewCall,Call::FreeCall

This is my code:

    class ObjectPool :public CriticalSection //
{
    T * pool = nullptr;
    unsigned __int32 size;
    __int64 next_free;
    std::vector<T *>free_objects;
public:
    ObjectPool(unsigned __int32 _size) :size(_size), next_free(size - 1);   
    ~ObjectPool();
    T * GetUnusedObject();
    void FreeObject(T * obj_to_free);
};

struct Call
{
    IX * ix;
    ...
        Call(IX * _ix) :ix(_ix){...}
    static Call * NewCall(IX * _ix)
    {
        Call * new_call = _ix->call_pool->GetUnusedObject();
        new_call->InitializeCall(_ix);
        return new_call;
    }
    static void FreeCall(Call * call_to_free)
    {
        call_to_free->ix->call_pool->FreeObject(call_to_free);
    }
};
class IX
{
    ...
public:
    ObjectPool<Call> * call_pool;
    ObjectPool<Session> * session_pool;
    IX()
    {
        call_pool = new ObjectPool<Call>(calls_pool_size);
        session_pool = new ObjectPool<Session>(calls_pool_size);
    }
    ~IX()
    {
        delete call_pool;
        delete session_pool;
    }

Errors: see declaration of 'IX'

error C2227: left of '->call_pool' must point to class/struct/union/generic type

error C2227: left of '->GetUnusedObject' must point to class/struct/union/generic type

error C2027: use of undefined type 'IX'

see declaration of 'IX'

Thanks a lot;

Aggregate initialization of an array of objects with `new` which compiler is right?

Supposedly, I have the following class:

class Foo { 
  int i;
public:
  Foo(int const i_) : i(i_) {}
  int geti() const { return i; }
};

and the following piece of code in main:

Foo* centroids = new Foo[5]{{1}, {2}, {3}, {4}, {5}};

GCC compiles and runs it with no problem demo, while CLANG gives a compile error demo

error: no matching constructor for initialization of 'Foo'

So which compiler is right?

print elements of std:: list using iterator c++

I'm trying to iterate through a std::list (containing) objects and print some methods but the compiler complaints that 'print': is not a member of 'std::shared_ptr<A>' However if i create an object std::shared_ptr<A> animal(*it); and call animal.print() it will work just fine why is that? below is the function i'm having trouble with (it's also a small portion of my very large program involving lots of polymorphism)

friend std::ostream& operator<<(std::ostream& out, const Hand& _hand) {         

            std::list< std::shared_ptr<A>>::const_iterator it = _hand.hand.begin();    
            std::shared_ptr<A> animal(*it);  
             animal.print(); //workss  
            while (it != _hand.hand.end()) {            
            it->print();   //doesn't work
                ++it;


            }

     return out;}

The list i'm iterating through is of type A (which is abstract) and contain objects of it's derived classes.

How to completely convert boost::asio code to C++11/asio without boost for deadline_timer?

My goal is to have my project to use asio library without boost, but use C++11. The example is to convert this server code to use Timeout. Here is what I did:

  1. boost::bind -> std::bind, _1 -> std::placeholders::_1
  2. most boost::asio::xxx -> asio::xxx
  3. boost::system::error_code -> asio::error_code

Now, there is 12 errors left all about deadline_timer :

deadline_timer input_deadline_;
input_deadline_.expires_at(boost::posix_time::pos_infin)

what is the correct code to use? I am using g++4.9.1/2, and newly downloaded asio library 1.10.6.

Why are implicitly and explicitly deleted move constructors treated differently?

What is the rationale behind the different treatment of implicitly and explicitly deleted move constructors in the C++11 standard, with respect to the implicit generation of move constructors of containing/inheriting classes?

Do C++14/C++17 change anything? (Except DR1402 in C++14)

Note: I understand what is happening, I understand that it is according to the C++11 standard's rules, I'm interested in the rationale for these rules that imply this behavior (please make sure not to simply restate that it is the way it is because the standard says so).


Assume a class ExplicitDelete with an explicitly deleted move ctor and an explicitly defaulted copy ctor. This class isn't move constructible even though a compatible copy ctor is available, because overload resolution chooses the move constructor and fails at compile time due to its deletion.

Assume a class ImplicitDelete which either contains or inherits from ExplicitDelete and does nothing else. This class will have its move ctor implicitly declared as deleted due to C++11 move ctor rules. However, this class will still be move constructible via its copy ctor. (Does this last statement have to do with resolution of DR1402?)

Then a class Implicit containing/inheriting from ImplicitDelete will have a perfectly fine implicit move constructor generated, that calls ImplicitDelete's copy ctor.

So what is the rationale behind allowing Implicit to be able to move implicitly and ImplicitDelete not to be able to move implicitly?

In practice, if Implicit and ImplicitDelete have some heavy-duty movable members (think vector<string>), I see no reason that Implicit should be vastly superior to ImplicitDelete in move performance. ImplicitDelete could still copy ExplicitDelete from its implicit move ctor—just like Implicit does with ImplicitDelete.


Here's the fully working example:

#include <utility>
#include <iostream>
using namespace std;

struct Explicit {
    // prints whether the containing class's move or copy constructor was called
    // in practice this would be the expensive vector<string>
    string owner;
    Explicit(string owner) : owner(owner) {};
    Explicit(const Explicit& o) { cout << o.owner << " is actually copying\n"; }
    Explicit(Explicit&& o) noexcept { cout << o.owner << " is moving\n"; }
};
struct ExplicitDelete {
    ExplicitDelete() = default;
    ExplicitDelete(const ExplicitDelete&) = default;
    ExplicitDelete(ExplicitDelete&&) noexcept = delete;
};
struct ImplicitDelete : ExplicitDelete {
    Explicit exp{"ImplicitDelete"};
};
struct Implicit : ImplicitDelete {
    Explicit exp{"Implicit"};
};

int main() {
    ImplicitDelete id1;
    ImplicitDelete id2(move(id1)); // expect copy call
    Implicit i1;
    Implicit i2(move(i1)); // expect 1x ImplicitDelete's copy and 1x Implicit's move
    return 0;
}

C++ auto type deduction

I'm trying to do automatic type deduction but it should only work if the inputs are fields.

I have declared a function like this:

template<class C> C gettype();

And I use it like this:

template<class L, class R, int F = CField<L,R>::is>
struct AddType {
    typedef decltype (gettype<L>() + gettype<R>()) type;
};

but I get a plethora of errors:

  1. that getType cannot be used as a parameter.
  2. that the compiler expects a ';' at the call to decltype. and that I need type specifiers.

etc.

Am I missing a lib or am I thinking about this all wrong?

thanks in advance!

Is it possible to not specify all template parameters if one of them is deduced?

Suppose I have a function like this:

template <typename T>
void f(T& x);

I can use it without specifying the type because of the type deduction:

f(5.0f); // same as f<float>(5.0f);

Suppose I change the function:

template <typename T, int N>
void f(T& x);

I now have to call it like this even if the type can be deduced

f<float, 5>(5.0f);

But I'd like to have something like this:

f<auto, 5>(5.0f); // or something like f<5>

So far I've found a way to do this:

template <int N>
struct F {
    template <typename T>
    static void f(T& x) {
         ...
    }
}

So I can now use:

F<5>::f(5.0f);

Is there any other way to do it?

How to add a char into a string

So I am creating an hangman game and want to add a char into a string. I want to add a char of guess to the gatherguess string until the gatherguess matches hangman. Feel free to add some helpful tips to my code that will make me better. Also if it would be more then nice if you can also give me some sample code with dynamic memory allocation.

    #include <stdio.h>
    #include <string.h>
    #include <iostream>     // std::cout

          #include <stdio.h>
#include <string.h>
#include <iostream>     // std::cout
#include <algorithm>    // std::for_each
#include <vector>
#include <set>
#include <string>
bool isitdone(std::string foo, std::string hang){
return foo == hang ? true : false ;
}
int main(){
std::string hangman;
char guess;
std::string gatherguess; //Get the letters guessed.
std::cin >> hangman; //Player enter the word to guess.
bool checkstatement; // Check to see if game is over.



for(int i =0; i < 10; ++i)
    {

std::cin >> guess; //Individual characters to guess
std::string doo;
int wordsin;
doo = hangman;

int y;
if(doo.rfind(guess) != std::string::npos)
    {


std::cout << "Right " << guess << " Is in the word"  << std::endl;


std::cout << std::endl;

checkstatement = isitdone(gatherguess,doo);// I want to add guess char into gatherguess 
//then check to see if gatherguess is equal to the word then the game will be complete
if(checkstatement == true)
    {
    return 0;
    }
    } else
    {
    std::cout << "Wrong" << std::endl;

    }



}
return 0;
}

Multiple classes, output

i got a class for a date and a class for a point of time. Now i want to combine them. My problem is that i'm not able to get the output working, it always uses the initialized date. Here is my code:

main.cpp

#include <iostream>
#include <iomanip>

#include "date.hpp"
#include "time.hpp"

using namespace std;

int main() {
Datum d1;
Datum d2(03, 12, 2015);

cout << "d1: " << d1 << endl;
cout << "d2: " << d2 << endl << endl;

zeit z1;
cout << "z1: " << z1 << endl;
zeit z2(d2, 23, 30);
cout << "z2: " << z2 << endl;
return 0;
}

date.cpp

#include "date.hpp"
#include <iostream>

Datum::Datum(unsigned int d, unsigned int m, unsigned int y)
{
    day = d;
    month = m;
    year = y;
    return;
}
Datum::Datum() : Datum(1, 1, 2000) { return; }
unsigned int Datum::getday() { return day; }
unsigned int Datum::getmonth() { return month; }
unsigned int Datum::getyear() { return year; }

std::ostream& operator<<(std::ostream& os, Datum& z)
{
    os << z.getday() << ".";
    os << z.getmonth() << ".";
    os << z.getyear();
    return os;
}

date.hpp

#ifndef DATUM_HPP_
#define DATUM_HPP_
#include <iostream>

class Datum {
private:
    unsigned int day;
    unsigned int month;
    unsigned int year;
public:
    Datum(unsigned int, unsigned int, unsigned int);
    Datum();
    unsigned int getday();
    unsigned int getmonth();
    unsigned int getyear();

    friend std::ostream& operator<<(std::ostream&, Datum&);
};
#endif

time.cpp

#include "time.hpp"
#include <iostream>

zeit::zeit(Datum date, unsigned int h, unsigned int m)
{
    std::cout << date.getday() << "." << date.getmonth() << "." <<  date.getyear() << std::endl;
    min = m;
    hour = h;
    return;
}
zeit::zeit() : zeit(Datum(),0,0) { return; }
unsigned int zeit::getmin() { return min; }
unsigned int zeit::gethour() { return hour; }

std::ostream& operator<<(std::ostream& os, zeit& z)
{
    os << z.date << ", ";
    if (z.gethour() < 10)
        os << "0" << z.gethour();
    else
        os << z.gethour();
    os << ":";
    if (z.getmin() < 10)
        os << "0" << z.getmin();
    else
        os << z.getmin();
    return os;
}

time.hpp

#ifndef ZEIT_HPP_
#define ZEIT_HPP_
#include "date.hpp"

class zeit {
private:
    unsigned int min;
    unsigned int hour;
    Datum date;
public:
    zeit(Datum, unsigned int, unsigned int);
    zeit();
    unsigned int getmin();
    unsigned int gethour();

    friend class Datum;
    friend std::ostream& operator<<(std::ostream&, zeit&);
};
#endif

This is the output i get:

d1: 1.1.2000
d2: 3.12.2015

1.1.2000
z1: 1.1.2000, 00:00
3.12.2015
z2: 1.1.2000, 23:30

What am i doing wrong? Ty for any help!

Is it possible to bind the second parameter of a lambda function?

I'm new to C++11 lambdas and what I would like to do is something like this, where a binary lambda is turned into a unary one by binding its second parameter.

#include <functional>

int main(int argc, char *argv[])
{
   auto lambda1 = [](int a, int b) { return a+b; };
   auto lambda2 = std::bind2nd(lambda1, 5);
   return 0;
}

Compilation fails with

error: no type named 'first_argument_type' in 'struct main(int, char**)::<lambda(int, int)>'
     class binder2nd

[How] can this be done?

c++11 multithreading memory error

I have the following code:

somefunc(string s, semaphore* sem) { 
     //some functionality
     sem->signal();
}

int main() {
    int num = 0;
    semaphore sem(0);
    vector<string> arr;
    for (string& s : arr) {
        ++num; 
        thread(somefunc, s, &sem).detach();
    }

    for (int i = 0; i < num; i++)
        sem.wait();
}

I am getting std::string allocation memory errors on the line where thread() is. Is there something wrong with this code? semaphore is a custom class that uses a mutex and a conditional variable.

static_assert on array values

Is it possible to have a compile-time check on array values?

example:

typedef enum
{
    dummy0 = 0,
    dummy1,
    dummy2
} eDummyEnum;

typedef struct
{
    eDummyEnum name;
    int value;
} sDummyStruct;

const sDummyStruct array[]=
{
    {dummy0, 3},
    {dummy1, 5},
    {dummy2, 6}
}

Is there any possibility to check if array[dummy1].name == dummy1 at compilation time?

Inheriting a type declaration in the presence of templates

Is there a way to declare types in a base class template and re-use those definitions in the child class template?

For example, consider the following attempt:

template <typename T_>
struct A {
    using T=T_;
};

template <typename T_>
struct B: public A<T_> {
    T a;
};

The compiler complains that using the type T in the definition of B is illegal. It doesn't wait for instantiation to see that this type is inherited from A. So, is there a way to declare types in a base class template and re-use those definitions in the child class template?

Initializer list of reference wrappers

I often encounter situations where I need to store lists of non-owning pointers or references to base class objects. Of course, I could do

#include <initializer_list>
#include <list>

class Base {};

class Derived {};

class Container {
public:
    void setObjects(const std::initializer_list<const Base *> objects); // Set objects_ member
private:
    std::list<const Base *> objects_; // Should store Base and Derived objects
};

Using std::reference_wrapper, I could also use

#include <initializer_list>
#include <list>
#include <functional> // for std::reference_wrapper

class Base {};

class Derived {};

class Container {
public:
    void setObjects(const std::initializer_list<std::reference_wrapper<const Base &> > objects); // Set objects_ member
private:
    std::list<std::reference_wrapper<const Base &> > objects_; // Should store Base and Derived objects
};

When I want to express the fact that an object (an instance of the Container class in my case) cannot exist without other objects (instances of the Base or Derived class), I tend to prefer the second alternative. However, it feels quite verbose to me and I have rarely seen it in other code. Is there any good reason I should prefer one alternative over the other?

What's the biggest data type in C++

I searched about biggest data type in c++, but each site wrote different data types. If there is an expert, can he (she) write answer. It's important. Thanks.

Smart pointer to an object that can change the pointer

I want to have a smart pointer to an object A that has a function f which can change the current object A that the smart pointer should point to. The function should work for all smart pointers and its ideal syntax is this:

//usage of f
std::unique_ptr<A> = p(new A);
p.reset(A->f(p.get()));

Raw pointers are used as argument and return value to make this work with any smart pointer. The flaw in this implementation is self-assignment caused by f returning the same pointer it was given. The self-assignment will result in the deletion of the current instance of A, which is not what we want. To remedy this we could use f like this:

//modified usage of f
std::unique_ptr<A> = p(new A);
A* temp = A->f(p.get());
if(p.get() != temp) {
  p.reset(temp);
}

This requires a temporary raw pointer right next to the smart pointer that might even point to the same object. To me it feels like bad design and I expect there to be a better solution than this.

I've also thought about passing a the smart pointer by reference, but this has some problems:

  • It does not force a return after resetting the smart pointers, which could cause memory corruption.
  • It forces the function to take a specific smart pointer as argument.

Am I overthinking this problem? Is using a temporary raw pointer to check if the smart pointer needs to be reset actually fine? Also, why does the reset function not already check for self-assignment?

'initializing': cannot convert from 'Array

Consider the following code:

#include <cstddef> //for std::size_t

template<class T, std::size_t Size>
class Array
{
private:
    T _data[Size];
public:
    template<class... Args>
    Array(Args&&... vals)
        : _data{ vals... }
    {}
};

int main()
{
    Array<int, 3> a = { 1, 2, 3 };
    Array<int, 3> b = { 4, 5, 6 };

    Array<Array<int, 3>, 2> arr = { a, b };
}

Everything works as expected for the first two objects (a and b) of the class.

Then I declare an array of arrays (2D array if you wish). So when the constructor of Array<Array<int, 3>, 2> arr; is executed I believe the template parameter T will be equal to Array<int, 3>. That way we should be able to successfully give Args&&... other objects of the same type. Then the parameter pack will expand.

So Array<Array<int, 3>, 2> arr; should essentially have a private member:

Array<int, 3> _data[2];

Apparently not, since I get the error that is in the title.

How can i run thread in c++? [duplicate]

This question already has an answer here:

I have my class:

class MyClass
{
public:
    MyClass();
    list<Obj> mainList;
    void MyMethod(){//This method changes elements in mainList};
}

void StartThread(MyClass& tmp)
{
    tmp.MyMethod();
}

main()
{
    MyClass test();
    std::thread thr(StartThread, std::ref(test));
    the.join(); //or detach(), both don't work
}

So can I do it this way using C++11?

The error that I get every time(LongPollSession = MyClass):

/usr/include/c++/4.9/functional: In instantiation of ‘struct std::_Bind_simple<void (*(std::reference_wrapper<LongPollSession*>))(LongPollSession)>’:
/usr/include/c++/4.9/thread:140:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (&)(LongPollSession); _Args = {std::reference_wrapper<LongPollSession*>}]’
main.cpp:19:47:   required from here
/usr/include/c++/4.9/functional:1665:61: error: no type named ‘type’ in ‘class std::result_of<void (*(std::reference_wrapper<LongPollSession*>))(LongPollSession)>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c++/4.9/functional:1695:9: error: no type named ‘type’ in ‘class std::result_of<void (*(std::reference_wrapper<LongPollSession*>))(LongPollSession)>’
         _M_invoke(_Index_tuple<_Indices...>)

C++ templates and friends, linker error

Why does the following code not compile (linker error, unresolved external symbol, class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class cClass<int> const &)" (??6@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AEAV01@AEBV?$cClass@H@@@Z))

#include <iostream>

template <class Type> class Class{
    public:
        friend std::ostream& operator<<(std::ostream& Stream, const Class& Op);
};

template <class Type> std::ostream& operator<<(std::ostream& Stream, const Class<Type>& Op){
    return(Stream);
}

int main(){
    Class<int> A;

    std::cout << A;

    return(0);
}

Why does the STL provide a const overload for std::container::begin and std::container::end functions?

Take any STL container in mind which uses iterators.

The following is valid:

iterator begin();
const_iterator begin() const;
const_iterator cbegin() const;

Now I don't understand why the second line exists. Could someone provide a nice example where iterator begin(); wouldn't work and it can't be replaced by const_iterator cbegin();... begging the need for const_iterator begin();?

A vector with members on the stack

I want this kind of interface

#include <vector>
void fun(std::vector<int> v){ }
int main(){
  fun({1, 2, 3, 4}); //<-- this type of invocation
}

instead of

void fun(int argc, int* args){ }
int main(){
   int a[]={1,2,3,4};
   fun(sizeof(a)/sizeof(int), a);
}

Can I make the vector go to the stack (or use something that behaves like an on-the-stack vector)?

(std::array appears to do the stack part, but it requires an explicit hardcoded size, and I don't want that.)

It's a premature optimization type of question, really, but I'm curious.

Destructor called before end of scope

The following program chrashes. But I don't really understand why. The boolean my_shared_resouce is in real life an asynchonous queue that eventually stops the loop inside of the thread via message passing. However, the following program crashes because the destructor seems to be called multiple times. And the first time it does is long before the sleep in the main() finishes. If i remove the delete my_shared_resource; I can see the destructor is called three times... However, following my current understanding the destructor should only be called when main() finishes.

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

using namespace std;

class ThreadedClass {

    public:

        ThreadedClass() {
            my_shared_resource = new bool(true);
        }

        virtual ~ThreadedClass() {
            delete my_shared_resource;
            cout << "destructor" << endl;
        }


        void operator()(){
            loop();
        }

        void stop() {
            *my_shared_resource = false;
        }

    private:

        void loop() {
            while (*my_shared_resource) {
                // do some work
                this_thread::sleep_for(std::chrono::milliseconds(1000));
            }
        }

        bool* my_shared_resource;
};

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

    ThreadedClass instance;
    std::thread t(instance);
    this_thread::sleep_for(std::chrono::milliseconds(1000));
    cout << "Did some work in main thread." << endl;
    instance.stop();
    t.join();
    return 0;
}

compiled with g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4

compiled as g++ --std=c++0x thread.cpp -pthread

Would someone please enlighten me what is wrong about this design.

How can a C++11 array not store its size?

From cplusplus.com :

Internally, an array does not keep any data other than the elements it contains (not even its size, which is a template parameter, fixed on compile time).

I understand that this means that using array is similar to using int[] and sizeof in the same scope. But is this code valid or is relying on undefined behavior?

class A {
    array<int, 10> arr;
    void setArr() {
        for (int& i : arr)
            i = 42;
    }
    void printArr() {
        for (int i : arr)
            cout << i << endl;
    }
};

How does the compiler know when to stop the foreach without storing the array size on the heap or stack? I ran it, the code works.

Use std::lock_guard with try_lock

Is there a way I can tell std::lock_gaurd to call try_lock instead of lock when it acquires the mutex?

The only way I could think of is to use std::adopt_lock:

if (!_mutex.try_lock())
{
    // Handle failure and return from the function
}
std::lock_guard<my_mutex_class> lock(_mutex, std::adopt_lock);

Is there a built-in solution for my problem rather then acquiring the lock explicitly and then give lock_guard the responsibility for releasing it?

samedi 28 novembre 2015

Stress test - Insert a large number of strings to a list

How could one do a 'stress test' of a linked list class that involves the insertion of a large number (thousands) of strings?

(The equivalent of a function that inserts a large number of integers by means of a for loop of incrementing values, if the linked list were to store integer values (i.e. for(i = 0; i < 5000; i++) LL.insert(i)).

C++ inheritance

So i have a C++ question about inheritance.

class X{
public:
 X()
 {
   cerr << "X()|";
 }
 X(const X& c)
 {
   cerr << "X(const X&)|";
 }
 ~X()
 {
   cerr << "~X()|";
 }
 X& operator=(const X& c)
 { 
   cerr << "X::op=|"; return *this;
 }
};

class B{
public:
 B()
 {
   cerr << "B()|";
 }
 B(const B& c):x1_(c.x1_)
 {
   cerr << "B(const B&)|";
 }
 virtual ~B()
 {
   cerr << "~B()|";
 }
 B& operator=(const B& c)
 { 
   cerr << "B::op=|"; 
   x1_=c.x1_;
   return *this;
 }
private:
 X x1_;
};

class D:public B{
public:
 D()
 {
   cerr << "D()|";
 }
 virtual ~D()
 {
   cerr << "~D()|";
 }
 private:
 X x2_;
};

Question 1:

when i run

B *pb = new B() result: X()|B()|

D *pd = new D() result: X()|B()|X()|D()|

why is that? B is not the child class of X?

Question 2:

D d(*pd)

*pd = d result: B::op=|X::op=|X::op=|

*pb = *pd result: B::op=|X::op=|

why is *pd = d have two X::op=| and *pb = *pd only have one X::op=|? can some one explain it?

Boost hana get index of first matching

So I am trying to make a library using boost::hana that requires the functionality to get the index of a element based on the value:

constexpr auto tup = boost::hana::make_tuple(3_c, boost::hana::type_c<bool>);

auto index = get_index_of_first_matching(tup, boost::hana::type_c<bool>);
//   ^^^^^ would be a boost::hana::int_<1>

Is there a possible way to do this? Better yet, is it already in hana and I don't know about it?

Thanks for the support!

How to find the answer to a XOR hash if I have the key & one number

I have a little routine that makes up a cumulative XOR hash. It's as if it is a savings account which gets bigger, cumulatively daily.. but in this sense we're saying the answer is being generated cumulatively and the key is always present.

I have taken a string of chars

pseudo code:

char H[10] = { "ABCDEFGHI", "\0" };

and I used 9 32-bit numeric keys to hash them in XOR encryption.

I did it like this:

for (i;i<10;i++)
    bitset<32> K ^= H[i] ^ NUMKEY[i];

Now this makes it impervious without the calculus plotting I did (see what I did there?) So K is an accumulation of calculus points, which are completely predictable according to calculus.

as far as I know, to undo it, I do

for (i;i<10;i++) {
    X=0;
    X ^= K ^ NUMKEY[i];
}

Is there other math involved? I think I have to take that X and do a little K - X to find the true derivative.

Here's the current routine I have for it. But I'm not getting what I'm looking for.

for_each (std::istreambuf_iterator<char>(in), \
    std::istreambuf_iterator<char>(), \
    [&] (long x) {
    t=s_nop(t,0);
    cred.push_back(t);
    alpha = static_cast<long>(cred[size]);
    delta = static_cast<long>(x);
    lambda ^= (alpha ^ delta);
    size++;
});

for (;i<=bn-1;i++) {
    alpha =  static_cast<unsigned long>(cred[bn-1-i]);
    delta ^= alpha ^ lambda;
    long hash1 = abs(lambda.to_ulong() + alpha.to_ulong() - 1);
    lambda = static_cast<unsigned long>(hash1);
    btrace.push_back(delta.to_ulong());
    delta=0;
}

Please have a safe and Merry Christmas. Thank you in advance!

Passing string to istringsream argument of a function

I would like to work with istringstream within a function and I want the istringstream to be initialized by a string passed by value. Can I avoid the explicit istringstream iss_input(string_input); in the function body?

void f(istringstream command){
}

int main(){
    f( string("create_customer 1 Ben Finegold") );
}

The above demonstrates what I want to achieve, but it does not work. The problem I am solving is command parsing.

"default constructor cannot be referenced" in Visual Studio 2015

I am facing a really weird error message in Visual Studio 2015. The following stripped down code:

struct A
{
    A(int val = 0)
    :
        x(val)
    {}

    int x = 0;
};

struct B: A
{
    static int y;
};

int B::y = 1;

struct C: B
{

};

int main()
{
    C c;
    return 0;
}

compiles without any problem on Clang. However Visual Studio 2015 IntelliSense gives the following error message:

the default constructor of "C" cannot be referenced -- it is a deleted function

Am I missing something in my code, or this is a true bug in Visual Studio?

In C++ class with copy & move ctor and copy assignment: no need for move assignment?

If I have a C++ class with copy and move constructors and copy assignment like so:

class Foo {
public:
    int A[];

    // custom ctor
    Foo(size_t N) {
        A = new A[N];
        for(int i = 0; i < N; i++) A[i] = i * i;
    }

    // copy ctor
    Foo(Foo& other) {
        size_t N = sizeof(other.A) / sizeof(int);
        A = new A[N];
        for(int i = 0; i < N; i++) A[i] = other.A[i];
    }

    // move ctor
    Foo(Foo&& other) {
        A = other.A;
        other.A = nullptr;
    }

    // copy assignment AND move assignment?
    Foo& operator=(Foo other) {
        std::swap(this.A, other.A);
        return *this;
    }

    // default dtor
    ~Foo() {
        delete[] A;
    }

Can I in this case simply avoid defining a move assignment operator and assume that still move assignment is taking place when possible? My reasoning behind that is: the copy assignment operator has to construct the Foo object defined as parameter. Now it can choose between the copy ctor and the move ctor as both are available. Thus if given an rvalue it should choose the move ctor and if given an lvalue it should choose the copy ctor. Is this correct?

Also: will this implementation work regarding the sizeof calculation of the array? If not, why not?

Vector find function working in Visual Studio but not in GCC

I have a function that does what I want it to do in Visual Studio, and I was transferring it to GCC to make sure everything worked there.

I now have a plethora of compilation errors stemming from my use of the std::find function.

I was hoping someone could take a look and help me figure out why I am only getting these errors in GCC. Here is a sample of the code: http://cpp.sh/6pky

// Example program
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <utility>
using namespace std;

int main()
{
   vector < list < pair <string, string> > > v;
   v.resize(15);
   pair<string, string> k ("foo", "bar");
   auto & whichList = v[2];
   if(find(begin(whichList), end(whichList), k) != end(whichList))
       cout << "true";

}

The part in question is find(begin(whichList), end(whichList), k).

I am getting an error that says I cannot compare a list of pairs with a pair (an issue I have been dealing a lot with this week) which I understand. I'm mostly curious as to why VS2015 not only doesn't recognize this error, but also performs the task appropriately.

Forcing template member function to instantiate

I have a class C in the namespace N with a public template member function F as follows:

namespace N {
    class C {
    public:
        template<int I>
        void F() {
            // ...
        }
    };
};

The values of I for N::C::F<I> are not known until runtime. However, the value of I is constrained such that 0 <= I < 2^8. I am looking for a way to force this function to expand the template to all 256 possible forms.

So far, I have manually created a static array within a second function of C that points to every possible function:

        template<int I>
        void F() {
            // ...
        }

        void G(int I) {
            static void(* const funcs[256])() = {
                F<0>, F<1>, F<2>, ...
            };

            funcs[I]();
        }

though I am left wondering if there is a better way. I already have a macro in N that is responsible for constructing a separate struct for each value of I (for use by F itself) and was looking if I could possibly integrate the instantiation of the template member function somehow in it:

    template<int> struct S;

    #define M(I, n) \
        template<> struct S<I> { \
            static const char name[] = #n; \
            /*
                Some how instantiate the function here, like (just guessing here):

                static const SEvaluator<I> eval = &C::F<I>;

                given

                template<int I>
                using SEvaluator = void(*)();
            */
        };

    M(0, "foo"); M(1, "bar");

    #undef M

My proposed method does not work as is and the compiler complains about F not being a constexpr. F manipulates several variables of C and calls external methods and could not be declared constexpr. Is there a way to salvage this or do I have to resort to my first hackish method?

MSVC2013 and variadic template methods with std::thread compilation error

I have a threads manager class with the folloing methods:

template <class _Fn, class... _Args>
void create_thread (_Fn&& fun, _Args&&... args)
{
    std::thread t (std::mem_fn(&MyClass::threads_entry<_Fn, _Args...>),
                    this, fun, args...);
}

template <class _Fn, class... _Args>
void threads_entry (_Fn&& fun, _Args&&... args)
{
  fun (std::forward <_Args>(args)...);
  perform_on_before_thread_exit_tasks();
}

In another class I'm trying to use it. This class has the following members:

void make_sure_thread_created ()
{
    m_threads.create_thread (
                    &MyClass2::thread_tasks,
                    this);
}

void thread_tasks ()
{
}

I get compilation error (MS VC2013):

error: C2064: term does not evaluate to a function taking 1 arguments

It points to this line of code:

fun (std::forward <_Args>(args)...);

Am I doing something wrong? Or is it the compiler bug? What can be done here?...

std::vector

I have some weird issues I cannot figure out. When I run the code below which takes a file.txt reads it line by line into a vector<string> and then compares each index to string "--" it does not make it to the comparison stage.

Further more, in the convert_file() under the for loop string m, has some weird behavior: string m = "1"; m+= "--"; ('--' inside vector) m+= "2"; will print to console 2--; which makes me think something is bugging out the vector. The 2 is replacing the 1, the first character. This makes it look like the vector is bugged.

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

vector<string> get_file(const char* file){
      int SIZE=256, ln=0;
      char str[SIZE];
      vector<string> strs;
      ifstream in(file, ios::in);
      if(!in){
        return strs;
      } else {
        while(in.getline(str,SIZE)){
          strs.push_back(string(str));
          ln++;
        }
      }
      in.close();
      return strs;
    }

void convert_file(const char* file){
      vector<string> s = get_file(file);

      vector<string> d;
      int a, b;
      bool t = false;
      string comp = "--";

      for(int i=0; i<s.size(); i++){
        string m = "1";
        m+= string(s.at(i));
        m+= "2";
        cout << m << endl;
        if(s.at(i) == comp){
          cout << "s[i] == '--'" << endl;
        }
      }
    }

int main(){
  convert_file("test.txt");
  return 0;
}

now when I run a test file to check a similar program:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main(){
  vector<string> s;
  s.push_back("--");
  s.push_back("a");

  for(int i=0; i<s.size(); i++){
    cout << "1" << s.at(i) << "2" << endl;
    if(s.at(i) == "--"){
      cout << i << "= --" << endl;
    }
  }
  return 0;
}

prints off 1--2, 0= --, 1a2. it works, it prints properly, and does the comparison. This leads me to think something is happening when I pull the line into a string.

Windows 7, cygwin64
g++ version 4.9.3
compile: D:\projects\test>g++ -o a -std=c++11 test.cpp

I have this code and i want to know how would i output the number of lookups or searches the program does to get to the value that was input

include

using namespace std;

int binarySearch(int [], int, int); // function prototype

const int SIZE = 16;

int main()

{

int found, value;

int array[] = {34,19,19,18,17,13,12,12,12,11,9,5,3,2,2,0}; // array to be searched

cout << "Enter an integer to search for:" << endl;

cin >> value;

found = binarySearch(array, SIZE, value); // function call to perform the binary search

// on array looking for an occurrence of value

if (found == -1)

cout << "The value " << value << " is not in the list" << "the number of look ups is "<< found/2 <

else

{

cout << "The value " << value << " is in position number "

<< found + 1 << " of the list" << " the number of look ups is "<< endl;

}

system ("pause");

return 0;

}

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

// binarySearch

//

// task: This searches an array for a particular value

// data in: List of values in an orderd array, the number of

// elements in the array, and the value searched for

// in the array

// data returned: Position in the array of the value or -1 if value

// not found

//

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

int binarySearch(int array[],int numElems,int value) //function heading

{

int first = 0; // First element of list

int last = numElems - 1; // last element of the list

int middle; // variable containing the current middle value of the list

while (first <= last)

{

middle = first + (last - first) / 2;

if (array[middle] == value)

return middle; // if value is in the middle, we are done

else if (array[middle] < value)

last = middle - 1; // toss out the second half of the array

//and search the first

else

first = middle + 1; // toss out the first half of the array

//and search the second

}

return -1; // indicates that value is not in the array

}

How to swap first and last digit in number in c++

please help me I am writing this code but it shows 0

#include <iostream>
using namespace std;

int main() {

    int n,a,b;
    cin>>n;
    b=n%10;

    while(n!=0) {
        a=n%10;
        n=n/10;     
    }
    a=b;
    b=a;
    cout<<n<<endl;
    return 0;
}

Is it legitimate to assign values to non-array objects with braces?

I discovered by accident that this works in the body of a program:(currently using g++ 5.2.0)

Vector4  pos;  
pos = {0.0, 1.1, 2.2, 3.3};  

The Vector4 class declares this data as named variables:

double  t, x, y, z;  

not as an array, and has no auto conversion cnstrs.

I guess memory storage is contiguous, so the compiler can figure out what to do. But is this legitimate usage, or can unallocated memory get used, or maybe some other gotchas possible?

Using swap inside assignment move operator

I c++ programming language 13.6.2 std::swap is used to implement move semantics the idea is below:

class deutscheSchweine{
 public:
  deutscheSchweine(){std::cout<<"DS\n";}
  deutscheSchweine& operator=(const deutscheSchweine& other){
   deutscheSchweine tmp;
   swap(*this, tmp);
   return *this;
  }
  deutscheSchweine(deutscheSchweine&& other){}
  deutscheSchweine& operator=(deutscheSchweine&& other){
   swap(*this, other);
   return *this;
  }
};


int main(){
deutscheSchweine ds;
deutscheSchweine ds2;
ds2 = ds;

I above example after calling assignment we can use move semantics to avid copying from temporary, but this example causes recursively calling move assignment. My question is can we use swap in move semantics but in some proper way?

C++11 random library in Android JNI

I am trying to compile an Android app with a native component that uses the C++ random library.

My Application.mk file is:

APP_STL := stlport_static
APP_CPPFLAGS += -std=gnu++11
NDK_TOOLCHAIN_VERSION := 4.8

On compilation I get the error:

[armeabi] Compile++ thumb: Project <= main.cpp
/home/user/project/main.cpp:12:18: fatal error: random: No such file or directory
#include <random>

Is the random library available for Android?

std::atomic.compare_and_exchange_strong() fails

I am pretty new to C++ and have to do some exercises on atomic operations. I am implementing a AtomicHashSet - but I get confused by compare_and_exchange_strong()behaving different than I would expect it.

As internal data structure I use an array of std::atomic-instances:

std::atomic<Item<T>> data[N] = {};

The essential part observing the problems is the following:

bool insert(const T &key) {
    if (keysStored.load() == N) {
        return false;
    }

    size_t h = this->hash(key);



    for (size_t i = 0; i < N; i++) {
        size_t pos = (h + i) % N;
        data[pos].load(); //No idea why that is needed...
        Item<T> atPos = data[pos].load();

        if (atPos.dataRef == &key) {
            return false;
        }
        if (atPos.dataRef == nullptr && atPos.state == BucketState::Empty) {
            Item<T> atomDesired(&key, BucketState::Occupied);

            if (data[pos].compare_exchange_strong(atPos, atomDesired)) {
                keysStored++;
                return true;
            }
        }
    }

    return false;
}

Item is defined like this:

enum class BucketState { Empty, Occupied, Deleted };

template<typename T>
struct Item {
Item(): dataRef(nullptr), state(BucketState::Empty) {}
Item(const T* dataRef, BucketState state) : dataRef(dataRef), state(state) {}

const T* dataRef;
BucketState state;
};

I do some assertion tests (inserting an element twice, checking keyStoredetc.). With this code they succeed - but if I remove the nonsense data[pos].load(); call they fail due to compare_exchange_strong() returning false. This strange failing behavior occurs only the first time the function is called...

I also checked with a debugger - the value of atPos is the same as in data[pos] - so in my understanding ces should do the exchange and returjn true.

Another question: Do I have to use a special memory order to ensure atomic (and therefore threadsafe) behaviour?

c++11: unique_ptr and new[]

If I'm right, unique_ptr is a kind of smart pointer, meaning that we don't need to delete it manually.
However, if we call the function release, it may leak memories.

For example:

unique_ptr<int> up(new int());
up.release();

Now we get memory leak because release wont' call delete.

However, here is something I can't understand:

unique_ptr<int[]> up(new int[10]);
up.release(); // call delete[] automatically

Why delete[] can be called automatically but delete can't be?

Can't find error in my c++ program

Here's the implementation, code is meant for prim's algo but is incomplete at the moment.

prim.h

#include "graph.h"
#include "header.h"

class prim {
private:
    vector <string> list;
public:
    prim ();
    prim (Graph *g);
    virtual ~prim ();
};

prim.cpp

#include "prim.h"
#define infinity std::numeric_limits <int>::infinity ()

prim::prim () {
}

prim::prim (Graph *g) {
    g -> printGraph ();
}

graph.h

#include "header.h"
#include <string>
using namespace std;

class vertex;
class edge {
private:
    vertex * origin;
    vertex * destination;
    int weight;
public:
    edge(vertex * org, vertex * dest, int weight) {
        origin = org;
        destination = dest;
        this->weight = weight;
    }

    vertex * getOrigin() {
        return origin;
    }
    vertex * getDestination() {
        return destination;
    }
    int getWeight() {
        return weight;
    }
};

class vertex {
private:
    string name;
    vector<edge> edges;
    int cost_of_each_node;
    bool source;
public:
    vertex(string id) {
        name = id;
        cost_of_each_node = NULL;
        source = false;
    }

    vertex(string id, int cost) {
        name = id;
        cost_of_each_node = cost;
        source = false;
    }

    vertex(string id, int cost, bool source) {
        name = id;
        cost_of_each_node = cost;
        this -> source = source;
    }

    void update_cost (int new_cost) {

    }
    void addEdge(vertex * v, int dist) {
        edge newEdge(this, v, dist);
        edges.push_back(newEdge);
    }

    void printEdges() {
        cout << name << " : " << endl;
        for (int i = 0; i < edges.size(); ++i) {
            edge e = edges[i];
            cout << e.getDestination()->getName() << " - " << e.getWeight()
                    << endl;
        }
        cout << endl;
    }

    string getName() {
        return name;
    }
    vector<edge> getEdges() {
        return edges;
    }
    int getCost() {
        return cost_of_each_node;
    }
    bool if_source() {
        return source;
    }
};
class Graph {
private:
    //vector <vertex *> vertices;
    string name;
public:
    vector<vertex *> vertices;
    //vector <string>
    Graph() {
    }

    Graph(string name) {
        this->name = name;
    }

    void insert(vertex * v) {
        vertices.push_back(v);
    }

    void printGraph() {
        for (int i = 0; i < vertices.size(); ++i) {
            vertices[i]->printEdges();
        }
    }
    int return_size() {
        return vertices.size();
    }

    string getName() {
        return name;
    }
};
class data_for_graph {
public :
    data_for_graph (Graph * g) {
        vertex v1 = vertex("Seattle");
        vertex v2 = vertex("Portland");
        vertex v3 = vertex("Everett");
        vertex v4 = vertex("Lynnwood");
        vertex v5 = vertex("Northgate");
        vertex v6 = vertex("Bellevue");
        vertex v7 = vertex("Arlington");
        vertex v8 = vertex("Bellingham");


        vertex *vp1 = &v1;
        vertex *vp2 = &v2;
        vertex *vp3 = &v3;
        vertex *vp4 = &v4;
        vertex *vp5 = &v5;
        vertex *vp6 = &v6;
        vertex *vp7 = &v7;
        vertex *vp8 = &v8;


        v1.addEdge(vp2, 100);
        v1.addEdge(vp6, 20);
        v2.addEdge(vp1, 100);
        v3.addEdge(vp1, 30);
        v3.addEdge(vp4, 10);
        v3.addEdge(vp7, 20);
        v4.addEdge(vp5, 15);
        v5.addEdge(vp1, 10);
        v6.addEdge(vp1, 20);
        v8.addEdge(vp7, 45);


        g -> insert(vp1);
        g -> insert(vp2);
        g -> insert(vp3);
        g -> insert(vp4);
        g -> insert(vp5);
        g -> insert(vp6);
        g -> insert(vp7);
        g -> insert(vp8);


        g -> printGraph();
    }
};

#endif /* SRC_GRAPH_H_ */

the error shown by gcc (windows, minGW) is : C:\Users\cortana\AppData\Local\Temp\ccpIsRfk.o:Controller.cpp:(.text+0xaa): undefined reference to `prim::prim(Graph*)' collect2.exe: error: ld returned 1 exit status

The correct way of returning std::unique_ptr to an object of polymorphic class

Let's say I have the following hierarchy of classes:

struct Base 
{
};

struct Derived : public Base 
{ 
    void DoStuffSpecificToDerivedClass() 
    {
    } 
};

And the following factory method:

std::unique_ptr<Base> factoryMethod()
{
    auto derived = std::make_unique<Derived>();
    derived->DoStuffSpecificToDerivedClass();
    return derived;
}

The problem is, the return statement does not compile, because std::unique_ptr does not have a copy constructor with covariance support (which makes sense since it does not have any copy constructors), it only has a move constructor with covariance support.

What is the best way to make solve this problem? I can think of two ways:

return std::move(derived); // 1
return std::unique_ptr<Base>(derived.release()); // 2

P.S. I'm using Visual C++ 2013 as my compiler. The original error message looks like this:

Error   1   error C2664: 'std::unique_ptr<Base,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : cannot convert argument 1 from 'std::unique_ptr<Derived,std::default_delete<Derived>>' to 'std::unique_ptr<Derived,std::default_delete<Derived>> &&'

c++ deleting static objects

I am just learning C++, and I'm having some trouble with memory leaks. I am using Visual Studio express, and I have enabled the crtdbg commands to dump memory leaks when the program closes. I cannot for the life of me, though, see why this particular line is being marked as a memory leak.

I have a class for Resource, and it contains a

static std::unordered_map< std::string, std::unique_ptr < Resource >> RESOURCE_LIBRARY;

This contains the definitions of the available resources, and then a factory method makes new resources based on these definitions when new resources are needed.

I then have a method that populates this map like this:

std::unique_ptr< Resource > lResource = std::unique_ptr< Resource >(new Resource(0, 0));
Resource::RESOURCE_LIBRARY["blue"] = std::move(lResource);

The problem I am seeing is that these lines to populate the map are the source of the memory allocation that isn't cleared up, according to Visual Studio. I have tried a method to free this like this:

for (auto it = RESOURCE_SOURCE_LIBRARY.begin(); it != RESOURCE_SOURCE_LIBRARY.end(); it++)
{
    it->second.reset();
}

but I still get the same messages out. I am sure that I must be missing/misunderstanding something here, so any help would be appreciated.

map [] operand doesn't work c++

hi my code looks something like this

class State
{
public:
    State * create(void);
};

typedef State * (*createFunc)(void);
class Registery
{
private:
   static std::map<std::string, createFunc> registery()
public:
   static void register_func(std::string key, createFunc func)
   {
       registery[key] = func;
   }
   static State * create(std::string key)
   {
       return registery[key]();
   }
};

int main()
{
   Registery::register_func("state", State::create);
   State * s = Registery::create("state");
}

the problem is that when I try to compile it I receive this error:

error: no match for ‘operator[]’ (operand types are ‘std::map< std::basic_string< char>, State* (*)()>()’ and ‘std::string {aka std::basic_string< char>}’)

as far as I can see the types match so I don't really understand why I have an error

When creating an instance of a derived class, is an instance of the base class being made too? [duplicate]

This question already has an answer here:

When creating an instance of a derived class, is an instance of the base class being made too?

For example:

class a {
public:
    void baz();
    int zxcv = 5;
};

class b: public a{
public:
    void foo();
};

int main(){
    b bar;
    bar.foo();
    bar.baz(); //how can bar have access to baz() if no instance a is created?
    bar.zxcv; //same, how can it access a non static member without an instance?
}

How to automate creation of tuples of template classes based on elements of an array?

I have an std::array that is filled with all the types of an enumeration. I'd like to implement my tuples based on this.

class CompBase
{
public:
    enum CompType{
        INPUT,
        GRAPHICS
        // ( + 5-10 additional types)
    };

    static const std::array<CompType, 2> compTypeArr;
};

const std::array<CompBase::CompType, 2> CompBase::compTypeArr =
{
    CompBase::INPUT,
    CompBase::GRAPHICS
};

template<CompBase::CompType compType_e>
class CompHolder {}; // owns one component

template<CompBase::CompType compType_e>
class CompContainer {}; // references N components

class CompInterface
{
    // ...
private:
    std::tuple // I want to automate this,
    <
        CompHolder<CompBase::INPUT>,
        CompHolder<CompBase::GRAPHICS>
    > compHolders;
};

class CompHandler
{
    // ...
private:
    std::tuple // and this process, based on the predefined array
    <
        CompCont<CompBase::INPUT>,
        CompCont<CompBase::GRAPHICS>
    > compContainers;
};

To my understanding std::make_tuple is not even constexpr before c++14 ref so I'm not sure if this is possible at all since I'd need a c++11 method. The presence of the array is I think sort of mandatory because an enumeration alone doesn't provide the necessary functionality for something like this.

When creating an instance of child class, is an instance of the parent class being made too?

When creating an instance of child class, is an instance of the parent class being made too?

If not then the child only have access to static public (and protected) functions of the parent?

For example:

class a {
public:
    void baz();
    class b {
    public:
        void foo();
    };
};

int main(){ 
    a::b bar; //is an instance of a being made too?
    bar.foo();
}