Other than opening a disassembly view, is there any decent mechanism or tool to determine quickly whether LLVM actually inlined methods in a CPP file (i.e., outside the actually class declaration) designated with the 'inline' option?
jeudi 31 août 2017
Why do the max values of long and long long produce the same output?
#include <iostream>
using namespace std;
#include <climits>
int main () {
int n_int = INT_MAX;
short n_short = SHRT_MAX;
long n_long = LONG_MAX;
long long n_llong = LLONG_MAX;
cout << "int is " << sizeof (int) << " bytes." << endl;
cout << "short is " << sizeof n_short << " bytes." << endl;
cout << "long is " << sizeof n_long << " bytes." << endl;
cout << "long long is " << sizeof n_llong << " bytes." << endl;
cout << endl;
cout << "Maximum values:" << endl;
cout << "int: " << n_int << endl;
cout << "short: " << n_short << endl;
cout << "long: " << n_long << endl;
cout << "llong: " << n_llong << endl << endl;
//cout << endl;
cout << "Minimum int value = " << INT_MIN << endl;
cout << "Maximum int value = " << INT_MAX << endl;
cout << "Bits per byte = " << CHAR_BIT << endl;
return 0;
}
OUTPUT: The long and long long variables are producing the exact same maximum values, I'm not sure why. The long value is supposed to output the maximum value of 2147483647.
int is 4 bytes.
short is 2 bytes.
long is 8 bytes.
long long is 8 bytes.
Maximum values:
int: 2147483647
short: 32767
long: 9223372036854775807
llong: 9223372036854775807
Minimum int value = -2147483648
Maximum int value = 2147483647
Bits per byte = 8
moving a unique_ptr into a vector
I have a function that looks similar to this
void resolve_dependencies(std::vector<std::unique_ptr<LoadedPlugin>>& result, std::vector<std::unique_ptr<LoadedPlugin>>& source, std::unique_ptr<LoadedPlugin>&& plugin)
{
auto p = plugin.get();
auto cur_pos = result.insert(result.begin(), std::move(plugin));
... more code ...
}
It moves the loaded plugin objects around in the result vector, doing a topological sort on them. My problem is that I get the following error on the result.insert line.
Error C2280 'std::unique_ptr<LoadedPlugin,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function
It is clear to me that something is trying to copy any of the unique_ptrs, but I cannot figure out why as I move the unique_ptr into the vector. Since I insert it with the insert function, the vector will try to move all objects to the right of it to a new memory location but should that not bve handled precisely through a move operation rather than a copy operation since c++11?
I have the same issue if I try to push_back the unique pointer instead. All I can think of is that something regarding my LoadedPlugin object is triggering this strange behaviour, but in this case nothing should be called on it right? The compiler and standard library is the ones that come with Microsoft Visual Studio Community 2017 Preview, Version 15.30, Preview 7.0.
C++: implementation-defined accepted physical source file characters
According to the C++14 standard,
§2.2.1.1 [...] The set of physical source file characters accepted is implementation-defined. [...] Any source file character not in the basic source character set is replaced by the universal-character-name that designates that character. [...]
Does it means that the C++ standard gives not implementation-defined or conditionally-supported support for non UCS/Unicode characters? For example, a physical source file encoding including characters without corresponding UCS code point.
The only think I can think of is, if that were the case (the compiler supports non UCS character through non UCS encodings), the compiler had to use the private UCS ranges to map those physical characters, but anyway, that solution doesn't fit to the "universal-character-name that designates that character" part, because universal-character-names inside private ranges doesn't define any specific character at all.
Forwarding reference vs const lvalue reference in template code
I've recently been looking into forwarding references in C++ and below is a quick summary of my current understanding of the concept.
Let's say I have a template function foo
taking a forwarding reference to a single argument of type T
.
template<typename T>
void foo(T&& arg);
If I call this function with an lvalue then T
will be deduced as T&
making the arg
parameter be of type T&
due to the reference collapsing rules T& && -> T&
.
If this function gets called with an unnamed temporary, such as the result of a function call, then T
will be deduced as T
making the arg
parameter be of type T&&
.
Inside foo
however, arg
is a named parameter so I will need to use std::forward
if I want to pass the parameter along to other functions and still maintain its value category.
template<typename T>
void foo(T&& arg)
{
bar(std::forward<T>(arg));
}
As far as I understand the cv-qualifiers are unaffected by this forwarding. This means that if I call foo with a named const variable then T
will be deduced as const T&
and hence the type of arg
will also be const T&
due to the reference collapsing rules. For const rvalues T
will be deduced as const T
and hence arg
will be of type const T&&
.
This also means that if I modify the value of arg
inside foo
I will get a compile time error if I did infact pass a const variable to it.
Now onto my question. Assume I am writing a container class and want to provide a method for inserting objects into my container.
template<typename T>
class Container
{
public:
void insert(T&& obj) { storage[size++] = std::forward<T>(obj); }
private:
T *storage;
std::size_t size;
/* ... */
};
By making the insert
member function take a forwarding reference to obj
I can use std::forward
to take advantage of the move assignment operator of the stored type T
if insert
was infact passed a temporary object.
Previously, when I didn't know anything about forwarding references I would have written this member function taking a const lvalue reference: void insert(const T& obj)
.
The downside of this is that this code does not take advantage of the (presumably more efficient) move assignment operator if insert
was passed a temporary object.
Assuming I haven't missed anything.
Is there any reason to provide two overloads for the insert function? One taking a const lvalue reference and one taking a forwarding reference.
void insert(const T& obj);
void insert(T&& obj);
The reason I'm asking is that the reference documentation for std::vector
states that the push_back
method comes in two overloads.
void push_back (const value_type& val);
void push_back (value_type&& val);
Why is the first version (taking a const value_type&
) needed?
In C++, why do I get different results using or not reference as result value?
class point
{
private:
double x,y;
public:
point(double x=0.0, double y=0.0)
{
this->x=x;
this->y=y;
}
point operator++()
{
this->x=this->x+1.0;
this->y=this->y+1.0;
return *this;
}
point& operator++(int)
{
point p=point(this->x, this->y);
++(*this);
return p;
}
ostream& operator<< (ostream& o)
{
o << "X: " << this->x << endl << "Y: " << this->y;
return o;
}
friend ostream& operator<< (ostream& o,point p)
{
o << "X: " << p.x << endl << "Y: " << p.y;
return o;
}
};
int main() {
point p=point();
p++ << cout << endl; // first output
cout << p++ << endl;// second output
}
I don't understand why the first output is incorrect (X: 6.95333e-310 Y: 6.95322e-310), while the second one is correct (X: 1 Y: 1).
And why this problem is solved by removing &
at the end of the return value of the post-increment operator?
C++: elegant "polymorphism" with STL types and custom types?
Let's say I have a custom implementation of std::vector
named my_vector
, and they have the same interface.
There are many functions that take std::vector
(or its pointer/reference) as input. I want to make as little modification as possible to these functions, while allowing them to accept either std::vector
or my_vector
.
Replacing these functions with function templates is a way to go, but there seem to be a lot of change (and hence difficult to rollback), and they can't do type checking unless I use std::is_same
to further complicate them. Function overloading is another alternative, but it entails duplicating the code, and is also difficult to rollback the change.
Question: can I design a wrapper type Vector
for std::vector
and my_vector
, and let those functions accept Vector
(or its pointer/reference) instead? But the problem with polymorphism is std::vector
can't inherit a custom class.
Ideally, the code should similar to this (not required to be the same) :
Definition of function:
// void foo(std::vector vec) {...} // old
void foo(Vector vec) {...} // new
Use the function:
std::vector<char> stdvec(5,'a');
my_vector<char> myvec(5,'a');
...
foo(stdvec);
foo(myvec);
Thanks!
Difference between constexpr and static constexpr global variable
In the C++11 standard, what is the difference between constexpr
and static constexpr
global variables when defined in a header? More specifically, when multiple translation units include the same header, which declaration (if any) is guaranteed to define the same variable across the translation units?
e.g.,
cexpr.h:
#ifndef CEXPR_H
#define CEXPR_H
constexpr int cint = 1;
static constexpr int scint = 1;
#endif
a.cpp:
#include "cexpr.h"
b.cpp:
#include "cexpr.h"
Simulate constructor behaviour for virtual methods
I am currently working on a small private project using C++ i came up with the following structure:
#include <iostream>
class A
{
std::vector<int> vec;
protected:
virtual bool onAdd(int toAdd) {
// should the 'adding' be suppressed?
// do some A specific checks
std::cout << "A::onAdd()" << std::endl;
return false;
}
public:
void add(int i) {
if(!onAdd(i)) {
// actual logic
vec.push_back(i);
}
}
};
class B : public A
{
protected:
bool onAdd(int toAdd) override {
// do some B specific checks
std::cout << "B::onAdd()" << std::endl;
return false;
}
};
In this example onAdd
is basically meant to be a callback for add
, but in a more polymorphic way.
The actual problem arises when a class C
inherits from B
and wants to override onAdd
too. In this case the implementation in B will get discarded (i.e. not called) when calling C::add
. So basically what I would like to achieve is a constructor-like behaviour where I am able to override the same method in different positions in the class hierarchy and all of those getting called.
My question now is: Is there a possibility/design to achieve this? I am sure that it wouldn't be as easy as cascading constructors, though.
Note: Don't focus too much on the add
example. The question is about the callback like structure and not if it makes sense with an add
.
mercredi 30 août 2017
c++ - Sharing Data Among Threads
I am writing a Windows 10 application that collects data from 4 different sensors (encoders and IMUs) via serial. I am writing this in Visual Studio in c++11. I have one thread per sensor that continuously pulls data from it in an infinite loop.
As I am new to this, I am currently struggling to somehow 'collect' the data in a single thread. I have found that I can use conditional variables to signal another thread (in my case I assume I would be signaling the main thread when each sensor is complete). In this scenario, would I have to store the data in a global variable and protect it with a mutex as I write into it (from the sensor thread) and read from it (in the main loop)?
I worry, however, that this process may be too slow for my application (each sensor gets new data every 1-2 ms), and so in the process of locking the data while the main thread reads, I would lose some data. Would it make sense to (within each sensor thread) store the data in a local variable and then copy this variable to a global variable, and have the main thread only read from the 2nd variable?
I apologize if these are stupid questions, but I really need help. Any example code would be extremely appreciated.
template metaprogramming static member function cannot get const static value of class
I am trying to generate numbers in compile time and tried templates. But when I use constexpr static
member variable instead of enum
, and in a static
member function where I try to push it into a std::vector
, the compiler told me the linker was unable to link.
For example, here is a simple program to calculate factorial of n
.
#include <iostream>
#include <vector>
template <uint64_t n> struct factorial {
constexpr static uint64_t value = factorial<n - 1>::value * n;
static void put(std::vector<uint64_t> &v) {
factorial<n - 1>::put(v);
v.push_back(value);
}
};
template <> struct factorial<0> {
constexpr static uint64_t value = 1;
static void put(std::vector<uint64_t> &v) {
v.push_back(1);
}
};
int main() {
using namespace std;
vector<uint64_t> v;
factorial<10>::put(v);
for (auto fact: v)
cout << fact << endl;
return 0;
}
This will produce link fail information with both g++ 7.1 and clang 4.0, so I thought it was not a bug. And when I change constexpr static
to enum
like
template <uint64_t n> struct factorial {
enum { value = factorial<n - 1>::value * n };
static void put(std::vector<uint64_t> &v) {
factorial<n - 1>::put(v);
v.push_back(value);
}
};
template <> struct factorial<0> {
enum { value = 1 };
static void put(std::vector<uint64_t> &v) {
v.push_back(1);
}
};
It compiles and links and runs pretty well.
I am wondering whether C++ standards mentioned about this.
Stack overflow error c++ after vectorization
I get a continuous stack overflow error when trying to test this little program to test the performance difference between Structure of Arrays vs Array of Structure. I'm clearly doing something wrong, but I have a really hard time figuring it out. Is anyone able to help?
#include "stdafx.h"
#include <vector>
#define NUM_ITEMS 10000000
struct Vector3 {
Vector3() : x(0.0f), y(0.0f), z(0.0f) {}
float x, y, z;
Vector3 operator+=(const Vector3& v) {
Vector3 v_new;
v_new.x = this->x + v.x;
v_new.y = this->y + v.y;
v_new.z = this->z + v.z;
return v_new;
}
};
struct SoA {
SoA() : pos(NUM_ITEMS), vel(NUM_ITEMS) {}
std::vector<Vector3> pos, vel;
};
struct AoS {
Vector3 pos, vel;
};
int main()
{
std::vector<AoS> entities[NUM_ITEMS];
for (int i = 0; i < entities->size(); i++) {
entities->at(i).pos += entities->at(i).vel;
}
SoA entityManager;
for (int i = 0; 1 < NUM_ITEMS; i++) {
entityManager.pos[i] += entityManager.vel[i];
}
return 0;
}
Can't end while loop: while(getline(cin, str))
I redirected the cin to a .txt file, and I tried to read line by line in the txt file with using while(getline(cin,str)).But i found that the while loop just keeps running and never ends, so what should I do?
I redirected cin and cout through the "run configuration" in eclipse:
My code is:
#include <iostream>
using namespace std;
int main() {
string line;
while(getline(cin, line)){
cout << line << endl;
}
cout << "hello" << endl;
return 0;
}
The problem is I can't get hello in the output.
С++: “invalid comparator” assert
Here is the code:
struct Payment
{
Payment(time_t time, float money) : mTime(time), mMoney(money) {}
bool operator==(const Payment& p) const // exact comparison
{
return mTime == p.mTime && mMoney == p.mMoney;
}
time_t mTime;
float mMoney;
};
std::vector<Payment> payments;
auto sortP = [](const Payment& p1, const Payment& p2) { return p1.mTime < p2.mTime || p1.mMoney <= p2.mMoney; };
std::sort(payments.begin(), payments.end(), sortP);
std::sort
(sometimes, not always) raises invalid comparator assert in Visual Studio 2015. What's wrong with the code?
Is it possible to pass overloaded method to std::thread
i am new to threading, i am trying to pass overloaded methods to std::thread like below example
#include <iostream>
#include <thread>
int do_calculation(int x)
{
std::cout<<x;
}
float do_calculation(float x)
{
std::cout<<x;
}
int main()
{
std::thread t1(do_calculation,20);
std::thread t2(do_calculation,200.0f);
return 0;
}
but the program is not compiling and throwing error that no matching function for call to 'std::thread::thread(<unresolved overloaded function type>, int)' std::thread t1(do_calculation,20);
Is there a way to call overloaded methods in thread?
Create typedef only when typedef exists in template parameter
I'm trying to create universal container wrapper.
template<typename type>
class ContainerWrapper
{
public:
using allocator_type = typename type::allocator_type;
using size_type = typename type::size_type;
using difference_type = typename type::difference_type;
using pointer = typename type::pointer;
using const_pointer = typename type::const_pointer;
using reference = typename type::reference;
using const_reference = typename type::const_reference;
using iterator = typename type::iterator;
using const_iterator = typename type::const_iterator;
using reverse_iterator = typename type::reverse_iterator;
using const_reverse_iterator = typename type::const_reverse_iterator;
using value_type = typename type::value_type;
iterator begin() noexcept { return container.begin(); }
const_iterator begin() const noexcept { return container.begin(); }
iterator end() noexcept { return container.end(); }
const_iterator end() const noexcept { return container.end(); }
reverse_iterator rbegin() noexcept { return container.rbegin(); }
const_reverse_iterator rbegin() const noexcept { return container.rbegin(); }
reverse_iterator rend() noexcept { return container.rend(); }
const_reverse_iterator rend() const noexcept { return container.rend(); }
const_iterator cbegin() const noexcept { return container.cbegin(); }
const_iterator cend() const noexcept { return container.cend(); }
const_reverse_iterator crbegin() const noexcept { return container.crbegin(); }
const_reverse_iterator crend() const noexcept { return container.crend(); }
protected:
ContainerWrapper() {}
type& getContainer() { return container; }
const type& getContainer() const { return container; }
private:
type container;
};
But not all containers have all kinds of iterators. Is it possible to expose container types only when they exists? Something like
using const_reverse_iterator = typename std::enable_if_t<std::is_class<typename type::const_reverse_iterator>::value, typename type::const_reverse_iterator>::type;
I could use C++11 only (gcc 4.7). Of course I could create different wrappers for different containers, but I prefer to have one universal wrapper.
c++11 object that can be passed as "double (*)[4]"
I need to call an function in an external library that has a signature:
void fn(double (*values)[4]);
but I would like to pass an object like std::vector<std::array<double, 4>>
and it must be c++11 compliant. How would I call this function?
Thread inside a class with member function from another class
Can someone tell me how can I run a new thread with member function from a object of diffrent class as a member function of this class ? What ever im trying to do Im still getting errors.
no match for call to '(std::thread) (void (Boo::*)(), Boo&)'|
no match for call to '(std::thread) (void (Foo::*)(), Foo*)'|
#include <iostream>
#include <thread>
using namespace std;
class Boo
{
public:
void run()
{
while(1){}
}
};
class Foo
{
public:
void run()
{
t1(&Boo::run,boo);
t2(&Foo::user,this);
}
void user();
~Foo(){
t1.join();
t2.join();
}
private:
std::thread t1;
std::thread t2;
Boo boo;
};
int main()
{
Foo foo;
foo.run();
}
Destructor in derived class marked as noexcept(false)
There is following code:
class Member
{
public:
~Member() noexcept(false) {}
};
class A
{
public:
virtual ~A() {}
};
class B : public A
{
public:
Member m;
};
The error is:
main.cpp:13:7: error: looser throw specifier for ‘virtual B::~B() noexcept (false)’
class B : public A
^
main.cpp:10:11: error: overriding ‘virtual A::~A() noexcept’
virtual ~A() {}
^
Why does the destructor in class B is marked as noexcept(false)? It seems that it somehow gets it from Member class. It was compiled by g++ 6.3.
How does
How does the signal()
function work? It doesn't appear to block when I run my program, yet somehow gets caught. Is it running a series of semaphores for each signal being caught? How will it effect my code if I run one signal
for each of the 64 types?
./libmylib.so: undefined reference to `submarinex::LIB::kCount'
I have 3 files in a directory. I will build ll.cc to libmylib.so, and build main.cc to myexe.
Use these command to build
g++ -Wall -g -fPIC -std=c++11 ll.cc -shared -o libmylib.so
g++ -Wall -g -std=c++11 main.cc -L. -lmylib -o myexe
But, g++ report a error when build myexe
:
./libmylib.so: undefined reference to `submarinex::LIB::kCount'
collect2: error: ld returned 1 exit status
Files:
ll.h
namespace submarinex {
class LIB {
public:
void Print();
private:
// If remove 'static', it also be OK regardless of using
// 'int min = std::min(101, kCount);
// std::cout << min << std::endl;'
// or
// 'std::cout << kCount << std::endl;'
static const int kCount = 100;
};
} // namespace submarinex
ll.cc
#include "ll.h"
#include <algorithm>
#include <iostream>
namespace submarinex {
void LIB::Print() {
int min = std::min(101, kCount);
std::cout << min << std::endl;
// If use this line, will success
// std::cout << kCount << std::endl;
}
main.cc
#include "ll.h"
int main(int argc, char **argv) {
submarinex::LIB lib;
lib.Print();
return 0;
}
Case 1
: If use these 2 lines in Print
, will report an error when link object of main.cc
int min = std::min(101, kCount);
std::cout << min << std::endl;
Case 2
: If use this line in Print
, will success
std::cout << kCount << std::endl;
If change
static const int kCount = 100;
to
const int kCount = 100;
it also be OK regardless of using Case1
or Case2
.
Why don't compilers merge redundant std::atomic writes?
I'm wondering why no compilers are prepared to merge consecutive writes of the same value to a single atomic variable, e.g.:
#include <atomic>
std::atomic<int> y(0);
void f() {
auto order = std::memory_order_relaxed;
y.store(1, order);
y.store(1, order);
y.store(1, order);
}
Every compiler I've tried will issue the above write three times. What legitimate, race-free observer could see a difference between the above code and an optimized version with a single write (i.e. doesn't the 'as-if' rule apply)?
If the variable had been volatile, then obviously no optimization is applicable. What's preventing it in my case?
Here's the code in compiler explorer.
Why an int pointer points to a const_casted const int pointer cannot really modify the value of const int? [duplicate]
This question already has an answer here:
Consider following codes
#include <iostream>
using namespace std;
int main() {
const int i = 10, *cpi =& i;
int *pi = const_cast<int*>(cpi);
*pi = 100;
cout<<*pi<<" "<<*cpi<<" "<<i<<endl;
// 100 100 10
return 0;
}
I used const_cast<int*>(cpi)
to cast cpi
from const int*
to int*
. And use const_casted int pointer to modify const int. The value of *cpi
and *pi
are as my expectation.
However, why i is still 10? Did compile create a second int value to store these 2 values?
mardi 29 août 2017
Set of Structs Missing an Element
#include <bits/stdc++.h>
using namespace std;
int dist[2];
struct cmp {
bool operator() (const int &a, const int &b) {
return dist[a] < dist[b];
}
};
set<int, cmp> s;
int main() {
dist[0] = 2;
dist[1] = 2;
s.insert(1);
s.insert(0);
for(set<int>::iterator it = s.begin(); it != s.end(); ++it) {
cout << *it << " " << dist[*it] << endl;
}
}
The above code outputs:
1 2
Why is this true? Should it not output:
1 2
0 2
Thank you!
std::is_base_of and virtual base class
Is there a way to identify whether or not a base class is a virtual base class?
std::is_base_of will identify a base class, but I'm looking for something like std::is_virtual_base_of to identify a virtual base class.
This is for SFINAE purposes where I want to use dynamic_cast (less performant) when std::is_virtual_base_of is true, and static_cast (more performant) when it is false.
Is there a #define for the C++ version being compiled? [duplicate]
This question already has an answer here:
As in the title,
is there a C++ preprocessor #define
that defines the C++ version being compiled? Like a compile with clang++ -std=c++11
produces a define __CPP_VERSION
or whatever.
C++11: Can I explicitly call a base class destructor to destroy the derived class?
I'm implementing a memory pool in C++11. All objects stored in the memory pool are required to inherit from the MemoryPoolObject class, but they may use multiple inheritance.
When I allocate a new object, I use malloc to create it, and then use the placement constructor - which I can do, because I know it's type (allocate() is a template function that takes the type as a template argument). I also store its size on the object on it (as a member variable of the MemoryPoolObject class).
When I deallocate the object, I want to call its destructor... but I no longer know the object type. I do know that it derives from MemoryPoolObject, which has a virtual destructor. So... if I make an explicit call to ~MemoryPoolObject(), will that do the right thing (including calling into the destructors of any multiply inherited base classes)?
Here's some code. It doesn't show how the unused objects get stored and retrieved in the pool... but that's really not relevant to the question at hand.
class BaseClass
{
public:
virtual ~BaseClass();
...
}
class MemoryPoolObject
{
public:
virtual ~MemoryPoolObject();
// In reality I don't just expose this, but for simplicity...
size_t m_ObjectSize;
}
class ChildClass : public BaseClass, public MemoryPoolObject
{
virtual ~ChildClass();
...
}
// allocation (simplified)
template<class T>
T* allocate()
{
size_t objectSize = sizeof(T);
T* obj = (T*)malloc(objectSize);
new(obj) T();
obj->m_ObjectSize = objectSize;
}
// deallocation (also simplified)
void deallocate(MemoryPoolObject* obj)
{
// Does this call ~BaseClass() and ~ChildClass()?
obj->~MemoryPoolObject();
}
Template parameter pack deduction when not passed as last parameter
Consider the following code:
#include <iostream>
#include <functional>
template<typename... Args>
void testfunc(const std::function<void (float, Args..., char)>& func)
{
}
int main(int argc, char* argv[])
{
auto func = [](float, int, char) {};
auto sfunc = static_cast<std::function<void (float, int, char)>>(func);
testfunc<int>(sfunc);
return 0;
}
I specify the type explicitly because (http://ift.tt/2x2dd3F):
When a parameter pack doesn't appear last in the parameter declaration, it is a non-deduced context. A non-deduced context means that the template arguments have to be given explicitly.
MSVC successfully compiles it, while both gcc and clang reject the code:
source_file.cpp: In function ‘int main(int, char**)’:
source_file.cpp:14:24: error: no matching function for call to ‘testfunc(std::function<void(float, int, char)>&)’
testfunc<int>(sfunc);
^
source_file.cpp:5:6: note: candidate: template<class ... Args> void testfunc(const std::function<void(float, Args ..., char)>&)
void testfunc(const std::function<void (float, Args..., char)>& func)
^
source_file.cpp:5:6: note: template argument deduction/substitution failed:
source_file.cpp:14:24: note: mismatched types ‘char’ and ‘int’
testfunc<int>(sfunc);
^
source_file.cpp:14:24: note: ‘std::function<void(float, int, char)>’ is not derived from ‘const std::function<void(float, Args ..., char)>’
Let's now make a slight change - let's remove the int
argument from our local func
, thereby causing the template argument pack to become empty:
#include <iostream>
#include <functional>
template<typename... Args>
void testfunc(const std::function<void (float, Args..., char)>& func)
{
}
int main(int argc, char* argv[])
{
auto func = [](float, char) {};
auto sfunc = static_cast<std::function<void (float, char)>>(func);
testfunc<>(sfunc);
return 0;
}
This time, all three compilers reject the code as incorrect. Tested with http://ift.tt/2sx4KA5 and a local Visual Studio installation.
Questions:
- Who is correct in the first case?
- How to achieve the desired effect - i.e., how can I explicitly specify a (possibly empty) parameter pack?
C++: Rules of Implicit and templated constructors
If I have the following code
template <bool X> struct B {
B() {}
B(const B<false> &b) {}
};
template <bool X> struct A {
A() {}
A(const A<false> &a) {}
A(const B<X> &b) {}
};
B<false> b;
A<true> a(b);
that does not compile, saying the call a(b)
is ambiguous, and rightfully so. It could call either
- implicit
A(const B<X> &b)
and explicitA(const A<false> &a)
- implicit
B(const B<false> &b)
and explicitA(const B<X> &b)
However, if I have this
template <bool X, typename Y> struct B {
B() {}
B(const B<false, Y> &b) {}
};
template <bool X> struct A {
A() {}
A(const A<false> &a) {}
template <typename Y>
A(const B<X, Y> &b) {}
};
B<false, void> b;
A<true> a(b);
it no longer gives an error. Am I to assume that A(const B<X, Y> &b)
is no longer a valid converting constructor because it is templated? And therefore the only possible path is #2?
Of what any other rules should I be aware, regarding converting constructors and templates?
Thanks
how to use std::bind with stl and save the return type?
I'm working on a class that schedules functions by binding them in a queue like that:
std::queue <void()> q;
template<typename R,typename... ArgsT>
void
schedule(R& fn, ArgsT&... args)
{
q.push(std::bind(fn, std::forward<ArgsT>(args)...) );
};
template<typename R,typename... ArgsT>
void
schedule(R&& fn, ArgsT&&... args)
{
q.push(std::bind(fn, std::forward<ArgsT>(args)...) );
};
so as you see I made the type of the queue void()
to make it hold any type of function objects but now I can't get the return when I execute it. what should I do to solve this?
Note: I don't want to use an external library like boost and I don't know what's the kind of function the user will pass it.
Why doesn't std::move on a std::unique_lock have any effect?
I have the following C++(11) code:
#include <mutex>
void unlock(std::unique_lock<std::mutex> && ulock)
{
}
int main(void)
{
std::mutex m;
std::unique_lock<std::mutex> ulock(m);
unlock(std::move(ulock));
if (ulock.mutex() == &m || ulock.owns_lock())
{
throw std::runtime_error("");
}
return 0;
}
What I can't figure out is why the mutex is still held after the return from unlock()
. My expectation is that the std::move()
causes the lock to go out of scope (and become unlocked by the destructor) upon return from the call to unlock()
. At the very least, it seems like the std::move()
should have caused ulock
to become "unbound" from the mutex m
.
What am I missing?
Travis CI: clang deduces copy constructor when it should deduce move constructor
I'm getting the following error on Travis CI (dist: trusty) with clang 3.9:
error: call to deleted constructor of 'Foo<Bar>'
return Foo<Bar>{Bar{}};
note: 'Foo' has been explicitly marked deleted here
Foo(const Foo<Bar>&) = delete;
However, the class
template<typename B>{
class Foo
[...]
Foo(const Foo<B>&) = delete;
Foo(Foo<B>&&) = default;
};
declares a move constructor, which should be called as Bar{}
is a temporary. What's particularly odd is that compiling with clang 3.9 works on my local machine. I am setting -std=c++11. I'd be grateful for any suggestions.
Calculating log-sum-exp function in c++
Are there any functions in the c++ standard library that calculate the log of the sum of exponentials? I am concerned specifically with the possibility that the summands will underflow. This is the situation where you are exponentiating negative numbers that have a large absolute value. I am using c++11.
How can I return char array with boost::optional
I try to return simple array with boost::optional
boost::optional<const char *> foo () {
char ar[100] = {};
return boost::make_optional(true, ar);
}
and I got the following error:
could not convert ‘boost::make_optional(bool, const T&) with T = char [100]’ from ‘boost::optional’ to ‘boost::optional’ return boost::make_optional(true, ar);
How can I handle such confusion?
initialize std::array with 'this' pointer
I am trying to initialize an array inside a template class and pass the this
pointer to all elements in the array. This is what my classes might look like:
template<int NUM> class outer_class;
template<int N>
class inner_class {
private:
outer_class<N> *cl;
public:
inner_class(outer_class<N> *num) {
cl = num;
}
void print_num() {
cl->print_num();
}
};
template<int NUM> class outer_class {
private:
int number = NUM;
// --> here I basically want NUM times 'this' <--
std::array<inner_class<NUM>, NUM> cl = { this, this, this, this };
public:
void print_num() {
std::cout << number << std::endl;
}
void print() {
cl[NUM - 1].print_num();
}
};
int main() {
outer_class<4> t;
t.print();
return 0;
}
How can I pass the this
pointer to all elements of inner_class
stored in the array of outer_class
(in C++11)?
Can I safely use GDAL with shared_ptr instead of Create/Destroy functions?
I am creating a shapefile in C++ 11 using GDAL.
Can I can safely make use of shared_pt< SomeGDALType > instead of SomeGDALType::CreateSomeGDALType() and SomeGDALType::DestroySomeGDALType(); ?
I noticed that the example code follows this pattern for all pointers the library needs:
OGRFeature *poFeature
poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() )
... other code that calls library function with above pointer ...
OGRFeature::DestroyFeature( poFeature );
//end of function.
Since I want my pointers to always be cleaned up nicely, I want to use a shared pointer like so:
std::shared_ptr<OGRFeature>poFeature(new OGRFeature(poLayer->GetLayerDefn()));
... other code that calls library function with poFeature.get() ...
//end of function
This obviates the problem of memory leaks if my code throws an exception. My code compiles, runs and creates a working shapefile.
My question is twofold:
Firstly; Is there a specific reason I want the memory to be allocated and de-allocated specifically by the library, (thereby allocating it possibly on another heap) which is what happens when I call the example's create and destroy functions?
Secondly; Can problems, beyond obvious programming mistakes on my end, arise as a result of my proposed alternative implementation?
printing vector elements : cout doesn't work while printf works
I'm trying to access the elements of a vector using this simple example:
#include <iostream>
#include <vector>
typedef std::vector<uint8_t> uint8_vec_t;
int main(void) {
uint8_vec_t v = {1, 2, 3, 4};
uint8_vec_t::iterator itr;
std::cout << "v.size() = " << v.size() << std::endl;
int i = 0;
for ( itr = v.begin(); itr != v.end(); ++itr, i++) {
std::cout << "std::cout: v[" << i << "] = " << v[i] << std::endl;
std::cout << "std::cout: *itr =" << *itr << std::endl;
printf("printf: v[%d] = %d\n", i, v[i]);
printf("printf: *itr = %d\n", *itr);
}
//
return 0;
}
And I get the following output:
v.size() = 4
std::cout: v[0] =
std::cout: *itr =
printf: v[0] = 1
printf: *itr = 1
std::cout: v[1] =
std::cout: *itr =
printf: v[1] = 2
printf: *itr = 2
std::cout: v[2] =
std::cout: *itr =
printf: v[2] = 3
printf: *itr = 3
std::cout: v[3] =
std::cout: *itr =
printf: v[3] = 4
printf: *itr = 4
I provide the same value to cout
and printf
but only printf
prints the value to the terminal. Why cout
doesn't print the value while I have no issue when using printf
?
Thanks for your help.
Array Initialisation Compile Time - Constexpr Sequence
I was reading this question on SO.
The question itself is not so interesting, but I was wondering whether it exists and how to implement a compile time solution.
Regard to the first sequence:
All numbers except the ones which can be divided by 3.
The sequence should be something like:
[1, 2, 4, 5, 7, 8, 10, 11, 13, 14, ...]
By induction, I've found the math formula for that sequence:
f(0) = 0;
f(x > 0) = floor[(3x - 1) / 2];
So I've implemented a C++ constexpr
function which generates the i-th number in the sequence:
#include <type_traits>
template <typename T = std::size_t>
constexpr T generate_ith_number(const std::size_t index) {
static_assert(std::is_integral<T>::value, "T must to be an integral type");
if (index == 0) return 0;
return (3 * index - 1) / 2;
}
Now I'd like to generate a "compile-time array/sequence" which stores the first N-th numbers of the sequence.
The structure should be something like:
template <typename T, T... values>
struct sequence {};
template <typename T, std::size_t SIZE>
struct generate_sequence {}; // TODO: implement
Questions (more than one, but related among them):
1) How to implement that kind of integer_sequence
?
2) Is it possible to build an std::array
from that integer_sequence
at compile time?
Dlib library can't find any STL template in iOS project (Xcode 8)
I'm trying to add Dlib library to my iOS project in Xcode 8.3.3.
I've tried to use this cocoapod and also tried to compile it myself but every time I get this: .../Pods/Headers/Public/dlib/dlib/image_processing/scan_image.h:6:10: 'vector' file not found
or even
.../Pods/dlib/build/install/include/dlib/algs.h:17:10: "Dlib requires C++11 support. Give your compiler the -std=c++11 option to enable it." .../Pods/dlib/build/install/include/dlib/algs.h:93:10: 'string' file not found
I've properly configured Xcode project and added every necessary dlib linker flags.
Project Build settings screenshot
Everything I'm trying to implement in Objective-C++ is contained in one .mm
file.
I've tried everything. Please help. Thank you.
CMake can not determine linker language for target: fileloader
I know there are already a few threads on this topic, however, after reading through many of them I have been unable to find a solution to my problem. I am working on a file loader/parser and am using CMake for the first time. My CMakeList.txt file is being used to import an XML parser (xerces) and currently looks like:
cmake_minimum_required(VERSION 2.8)
project(fileloader)
set(SRCS
Source.cpp
)
include_directories(./
${SPF_ROOT}/xerces/win64/include/xercesc/dom
)
add_executables(${PROJECT_NAME} ${SRCS})
add_library(HEADER_ONLY_TARGET STATIC XMLString.hpp XercesDOMParser.hpp DOM.hpp HandlerBase.hpp PlatformUtils.hpp)
set_target_properties(HEADER_ONLY_TARGET PROPERTIES LINKER_LANGUAGE CXX)
I am relatively new to c++ and completely new to CMake so hopefully I am missing something simple, but any and all help is greatly appreciated!
smart pointer for array c++ [on hold]
What smart pointer should be used when you want to create an array in C++11?
Let's say if you want to create a matrix which later on will be used a copy constructor, operator= and operator+.
convertion error in a method that return a lambda expression
this code works without problem
#include "iostream"
#include "functional"
std::function<double (double)> retFun(double* a) {
return [a](double x) { return x+*a; };
}
int main(){
double*e = new double(3);
std::cout << retFun(e)(3) << std::endl;}
but if i declare retFun in a object :
.h
class InternalVariables : public Page { private: std::function<double ()> retFun(double* a); };
.cpp
std::function<double ()> InternalVariables::retFun(double *a) { return [a](double b){ return b+ *a;}; }
i obtain the following error
error: could not convert ‘InternalVariables::retFun(double*)::__lambda44{a}’ from ‘InternalVariables::retFun(double*)::__lambda44’ to ‘std::function’ return [a](double b){ return b+ *a;};
memory allocated for std::vector which in a map can not be released.
I use some data structures to store images of defective products in an inspection application. The data structure store defect information in defectDB_ and use a "url" point to imageDB_, which use std::vector to store actual image data. The problem is: I use imageDB_.erase() to erase the element, but the vector's memory is not released, the memory usage increased very fast. The following is "DB" definition:
// sourceId[0~3],defectRect,defectImageUrl,defectString
using DefectVector = std::vector<std::tuple<int, QRect, QString, QString>>;
//image(data,w,h,pitch,channel)
using ImageData = std::tuple<std::vector<uchar>, int, int, int, int>;
// productId:defectVector
std::map<int,DefectVector> defectDB_;
// imageUrl:
std::map<QString,ImageData> imageDB_;
The following codes store some images into memory. The std::vector is used to store the actual image data.
if (!thumb.isNull())
{
QString key = QString("%1/%2/%3/%4").arg(id).arg(sourceId).arg(imageUrl).arg("thumb");
imageDB_[key] = std::make_tuple(std::vector<uchar>(), thumb.width(), thumb.height(), thumb.bytesPerLine(),
thumb.format() == QImage::Format_Grayscale8 ? 1 : 3);
// allocate a buffer
std::get<0>(imageDB_[key]).resize(thumb.height()*thumb.bytesPerLine());
// copy to the buffer
std::memcpy(std::get<0>(imageDB_[key]).data(), thumb.bits(), thumb.height()*thumb.bytesPerLine());
}
In the other place, I erased some items in imgeDB_ when there are too many images. The codes:
if (defectDB_.size() > MAX_DEFECTS_COUNT)
{
auto head = defectDB_.begin();
auto list = head->second;
for (auto t : list)
{
auto url = std::get<2>(t);
auto it = imageDB_.find(url);
if (it != imageDB_.end())
{
imageDB_.erase(it);
}
else {
qCritical() << "Missed image for image url:" << url;
}
}
defectDB_.erase(head);
}
It seems the memory allocated by
std::get<0>(imageDB_[key]).resize(thumb.height()*thumb.bytesPerLine());
is never released! Anyone can help me to figure it out?
How do I call an rvalue member function from another rvalue member function?
I'm trying to create a class that is only supposed to exist temporarily. I'm using this to create an interface similar to the partial application of a function. Here's a silly example of what I'm trying to do.
struct Adder {
explicit Adder(const int &leftOp)
: leftOp(leftOp) {}
int add(const int rightOp) const {
return leftOp + rightOp;
}
//note that addTwice calls add
int addTwice(const int rightOp) const {
return add(rightOp) + add(rightOp);
}
private:
const int &leftOp;
};
struct Calculator {
explicit Calculator(const int leftOp)
: leftOp(leftOp) {}
Adder add() const {
return Adder(leftOp);
}
void setLeftOp(const int newLeftOp) {
leftOp = newLeftOp;
}
private:
int leftOp;
};
The calculator is used like this.
Calculator myCalculator(4);
const int myNum = myCalculator.add().add(5);
std::cout << myNum << '\n'; // 9
I want to restrict the interface of Adder
so that it can only be called as above. I want the compiler to stop users from storing an Adder
in a variable.
auto myCalcPtr = std::make_unique<Calculator>(4);
const Adder adder = myCalcPtr->add();
myCalcPtr.reset();
//oh dear. Adder has a dangling reference to a member in Calculator
const int myNum = adder.add(5);
My immediate thought was to mark Adder::add
and Adder::addTwice
as &&
but I got compiler errors in Adder::addTwice
. The error was
No matching member function for call to `add`
Candidate function not viable: 'this' argument has type 'const Adder' but method is not marked const
So I added made both functions const &&
but still got the same error then I came to stackoverflow and asked
How do force all instances of Adder to always be a tempory?
My actual problem is much more complicated than the above example. I'm not a beginner asking about homework!
IPSEC using Windows
I am trying to create IPSEC server in windows to receive and send SIP messages over ESP. I am using Windows APIs like FwpmEngineOpen0, FwpmFilterAdd0 to create my own qucik mode SAs. After creating the SA, windows is not decrypting any ESP packets. Any idea how to proceed with this? I can post my code if needed.
Which processor to test C++11/C11 acquire release semantic
I am looking for a processor that performs read acquire/store release with the same semantic as specified in the C11/C++11 standards.
x86 processor synchronization is much too strong so that it is impossible to test a lock-free algorithm using acquire/release semantic.
The same seems to apply to ARM processor because this architecture offers either stronger or weaker read/store synchronizations. Maybe ARMv8.3 may offer the right semantic but I believe there are no ARMv8.3 processor on the market.
On which processor or architecture should I test a lock-free algorithm using acquire-release semantic?
Exception in debug mode when const member variable initialised in class declaration
#include <functional>
#include <map>
#include <string>
#include <iostream>
class X
{
public:
X()
{
std::cout << "Ctor\n";
}
private:
typedef std::map<std::string, std::function<void()>> ValidatorType;
const ValidatorType m_validators = ValidatorType
{
{
"some-string",
[]()
{
// validation code
std::cout << "Validating...\n";
}
}
};
};
int main()
{
std::cout << "Start...\n";
X x;
std::cout << "Complete...\n";
return 0;
}
The above code builds and runs successfully in debug and release mode on OS X using Xcode 7.2.1 and Clang 7.0.2.
It also builds and runs successfully in release mode on Windows 7 using Visual Studio Express 2013 for Windows Desktop.
However, it crashes when run in debug mode on Windows. An access violation occurs before the constructor finishes executing. The console output is as follows:
Start...
Ctor
If the initialisation of m_validators
is moved to the constructor initialiser list then the error goes away.
Could this be a compiler bug or is there something wrong with the declaration?
Is x+++y well-defined behaviour? [duplicate]
This question already has an answer here:
- What is i+++ increment in c++ 3 answers
The expression z = x+++y;
is parsed as x++ + y
because output of my program is :
x : 2
y : 2
z : 3
My code:
#include <iostream>
using namespace std;
int main()
{
int x = 1, y = 2, z;
z = x+++y;
cout<<"x : "<<x<<endl<<"y : "<<y<<endl<<"z : "<<z<<endl;
return 0;
}
So, is x+++y
well-defined behaviour?
lundi 28 août 2017
Threads - Mac vs Linux
Great!
I just finished my implementation on Mac with g++ / clang
Configured with: --prefix=/Applications/http://ift.tt/1d5DwEL --with-gxx-include-dir=/Applications/http://ift.tt/2h6IoD1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
and tested my code on linux
g++ (Debian 4.7.2-5) 4.7.2
running a relatively simple threading operation. What worked on mac, fails on linux now with :
terminate called after throwing an instance of 'std::system_error'
what(): Operation not permitted
#include <cstddef>
#include <memory>
#include <stdlib.h>
#include <iostream>
#include <thread>
#include <vector>
#include <stdexcept>
std::vector<std::thread> threads;
std::vector<std::tuple<std::size_t, std::size_t>> parts = splitRows(maxNumberThreads, elements);
for (std::size_t threadIndex = 0; threadIndex < maxNumberThreads; threadIndex++)
{
threads.push_back(std::thread(compute<T>,parts[threadIndex], numbers, std::ref(*this),std::ref(other),std::ref(target)));
}
with the thread function defined as. Adding prints into compute
it does not jump into the function at all... Any idea why this happens?
template<typename T>
void compute(const std::tuple<std::size_t,std::size_t> part,
const std::size_t numbers,
const MyClass<T>& m1,
const MyClass<T>& m2,
MyClass<T>& target){
I am compiling with
g++ -Wall main.cpp -o matrix.exe -std=c++11
but get the above runtime error. Any ideas how to fix this? I use std libraries only, nothing fancy...
What is the maximum number of dimensions allowed for an array ?What is the reason behind its limitation.?
what is the maximum number of dimensions that you can use when declaring an array?
For Example..
#include<iostream.h>
#include<conio.h>
{
int a[3][3][3][4][3];
clrscr();
a[3][3][3][4][3]=9;
}
so,how many time we declare it. What is limitation of it?? and What is reason behind it??
Valgrind showing memory leaks in OpenMPI ORTE and OPAL but nothing in the main program
I am currently debugging a very large program in Ubuntu 16.04 LTS which uses OpenMPI and have encountered some memory leaks. Using Valgrind, the error seems to be stemming from main (main.c:13)
(which is not part of the program), ORTE and OPAL which are sub packages of OpenMPI.
The question is whether this is a bug in the program or OpenMPI itself and whether this only occurs for some MPI method or MPI datatype.
Below is the output from Valgrind using the -g -O0 -fno-inline
C++ compiler flags and --tool=memcheck --leak-check=yes --track-origins=yes --leak-check=full
valgrind flags.
==42361== Memcheck, a memory error detector
==42361== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==42361== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==42361== Command: mpiexec -n 18 -output-filename test.txt dist/UM_Release/GNU_MPI-Linux/_nb_test_shortest -L -l 1 -r 0.01 -R 0.1
-s 1 -z 0 -B 0.5:30:0.1 -b 100 -i 300 -m 0.1 ../_DATA/Chicago
==42361== Parent PID: 42313
==42361==
==42361== Conditional jump or move depends on uninitialised value(s)
==42361== at 0x4C3E552: orte_get_attribute (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4C6ADF7: bind_in_place.isra.0 (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4C6C0D9: orte_rmaps_base_compute_bindings (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4C67581: orte_rmaps_base_map_job (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4EFCC10: opal_libevent2022_event_base_loop (event.c:1370)
==42361== by 0x404B30: orterun (orterun.c:1071)
==42361== by 0x403455: main (main.c:13)
==42361== Uninitialised value was created by a stack allocation
==42361== at 0x4C6ACE0: bind_in_place.isra.0 (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361==
==42361== HEAP SUMMARY:
==42361== in use at exit: 418,015 bytes in 2,008 blocks
==42361== total heap usage: 46,504 allocs, 44,496 frees, 33,545,201 bytes allocated
==42361==
==42361== 4 bytes in 1 blocks are definitely lost in loss record 5 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x3D66481021: strdup (in /lib64/libc-2.12.so)
==42361== by 0x4EE6516: opal_basename (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x79C99B9: ???
==42361== by 0x79C9AD4: ???
==42361== by 0x5DACEBE: ???
==42361== by 0x4C2396E: orte_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4040CE: orterun (orterun.c:818)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 8 bytes in 1 blocks are definitely lost in loss record 22 of 352
==42361== at 0x4A057BB: calloc (vg_replace_malloc.c:593)
==42361== by 0xA01C5E6: ???
==42361== by 0xA055D40: ???
==42361== by 0xA018EA1: ???
==42361== by 0x4C45DF0: pmix_server_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x5DAD3DD: ???
==42361== by 0x4C2396E: orte_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4040CE: orterun (orterun.c:818)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 8 bytes in 1 blocks are definitely lost in loss record 23 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0xA05E5EA: ???
==42361== by 0xA05626B: ???
==42361== by 0xA018EA1: ???
==42361== by 0x4C45DF0: pmix_server_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x5DAD3DD: ???
==42361== by 0x4C2396E: orte_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4040CE: orterun (orterun.c:818)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 11 bytes in 1 blocks are definitely lost in loss record 25 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x3D66481021: strdup (in /lib64/libc-2.12.so)
==42361== by 0x5DAC9B7: ???
==42361== by 0x4C2396E: orte_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4040CE: orterun (orterun.c:818)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 13 bytes in 1 blocks are definitely lost in loss record 29 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x3D66481021: strdup (in /lib64/libc-2.12.so)
==42361== by 0x79C91D9: ???
==42361== by 0x79C9335: ???
==42361== by 0x4EDCA96: mca_base_select (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4C5AF99: orte_plm_base_select (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x5DAC89B: ???
==42361== by 0x4C2396E: orte_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4040CE: orterun (orterun.c:818)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 14 bytes in 1 blocks are definitely lost in loss record 30 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4EEEC1A: opal_os_path (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4EF0ADD: opal_path_access (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4EF0E6C: opal_path_findv (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x79C999A: ???
==42361== by 0x79C9AD4: ???
==42361== by 0x5DACEBE: ???
==42361== by 0x4C2396E: orte_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4040CE: orterun (orterun.c:818)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 31 (24 direct, 7 indirect) bytes in 1 blocks are definitely lost in loss record 76 of 352
==42361== at 0x4A06C20: realloc (vg_replace_malloc.c:662)
==42361== by 0x4EE5932: opal_argv_append_nosize (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x79C92CA: ???
==42361== by 0x79C9335: ???
==42361== by 0x4EDCA96: mca_base_select (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4C5AF99: orte_plm_base_select (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x5DAC89B: ???
==42361== by 0x4C2396E: orte_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4040CE: orterun (orterun.c:818)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 39 bytes in 1 blocks are definitely lost in loss record 124 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x3D6646F41F: vasprintf (in /lib64/libc-2.12.so)
==42361== by 0x3D6644F307: asprintf (in /lib64/libc-2.12.so)
==42361== by 0x4EE687D: set_dest (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4EE7532: opal_cmd_line_parse (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4038FA: orterun (orterun.c:604)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 39 bytes in 1 blocks are definitely lost in loss record 125 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x3D6646F41F: vasprintf (in /lib64/libc-2.12.so)
==42361== by 0x3D6644F307: asprintf (in /lib64/libc-2.12.so)
==42361== by 0x4EE687D: set_dest (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4EE7532: opal_cmd_line_parse (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x405384: create_app (orterun.c:1395)
==42361== by 0x40507D: parse_locals (orterun.c:1241)
==42361== by 0x404220: orterun (orterun.c:866)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 42 (24 direct, 18 indirect) bytes in 1 blocks are definitely lost in loss record 140 of 352
==42361== at 0x4A06C20: realloc (vg_replace_malloc.c:662)
==42361== by 0x4EE5932: opal_argv_append_nosize (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x79C9A12: ???
==42361== by 0x79C9AD4: ???
==42361== by 0x5DACEBE: ???
==42361== by 0x4C2396E: orte_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4040CE: orterun (orterun.c:818)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 48 bytes in 1 blocks are definitely lost in loss record 172 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4EDC10B: mca_base_component_repository_open (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4EDB36A: mca_base_component_find (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4EE4F99: mca_base_framework_components_register (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4EE53A7: mca_base_framework_register (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4EE5410: mca_base_framework_open (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4F3FA81: patcher_query (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4F3F965: opal_memory_base_open (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4EE5484: mca_base_framework_open (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4EBEC9E: opal_init (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x403BAB: orterun (orterun.c:678)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 48 bytes in 1 blocks are definitely lost in loss record 173 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x87DE912: ???
==42361== by 0xBC84858: ???
==42361== by 0x4C53618: orte_iof_base_select (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x5DAD444: ???
==42361== by 0x4C2396E: orte_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4040CE: orterun (orterun.c:818)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 71 bytes in 1 blocks are definitely lost in loss record 190 of 352
==42361== at 0x4A06C20: realloc (vg_replace_malloc.c:662)
==42361== by 0x3D6646F3D2: vasprintf (in /lib64/libc-2.12.so)
==42361== by 0x3D6644F307: asprintf (in /lib64/libc-2.12.so)
==42361== by 0x4C5A4A8: orte_oob_base_get_addr (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DE7BD: ???
==42361== by 0x5DACD0C: ???
==42361== by 0x4C2396E: orte_init (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4040CE: orterun (orterun.c:818)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 195 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0x4C23637: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 196 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0x4C463D5: pmix_server_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x5DAC165: ???
==42361== by 0x4C23641: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 197 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0x4C463E0: pmix_server_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x5DAC165: ???
==42361== by 0x4C23641: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 198 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0x4C2EB93: orte_data_server_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x5DAC176: ???
==42361== by 0x4C23641: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 199 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0xB87DCFC: ???
==42361== by 0x4C4C2A5: orte_dfs_base_close (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4EE5568: mca_base_framework_close (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x5DAC18E: ???
==42361== by 0x4C23641: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 200 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0xB87DD07: ???
==42361== by 0x4C4C2A5: orte_dfs_base_close (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4EE5568: mca_base_framework_close (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x5DAC18E: ???
==42361== by 0x4C23641: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 201 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0xB6789A4: ???
==42361== by 0x4C4FBB5: orte_filem_base_close (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4EE5568: mca_base_framework_close (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x5DAC19A: ???
==42361== by 0x4C23641: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 202 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0xB678B49: ???
==42361== by 0x4C4FBB5: orte_filem_base_close (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4EE5568: mca_base_framework_close (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x5DAC19A: ???
==42361== by 0x4C23641: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 203 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0xBC84C10: ???
==42361== by 0x4C52E15: orte_iof_base_close (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4EE5568: mca_base_framework_close (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x5DAC1C4: ???
==42361== by 0x4C23641: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 204 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0x89E219B: ???
==42361== by 0x4C5152E: orte_grpcomm_base_close (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4EE5568: mca_base_framework_close (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x5DAC200: ???
==42361== by 0x4C23641: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 205 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0x4C5BCD6: orte_plm_base_comm_stop (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x79CA191: ???
==42361== by 0x4C5AED5: orte_plm_base_close (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4EE5568: mca_base_framework_close (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x5DAC218: ???
==42361== by 0x4C23641: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 80 bytes in 1 blocks are possibly lost in loss record 206 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C6C5ED: prq_cons (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x87DED18: ???
==42361== by 0x4C5BD06: orte_plm_base_comm_stop (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x79CA191: ???
==42361== by 0x4C5AED5: orte_plm_base_close (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4EE5568: mca_base_framework_close (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x5DAC218: ???
==42361== by 0x4C23641: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 96 (80 direct, 16 indirect) bytes in 2 blocks are definitely lost in loss record 211 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C2694F: orte_dt_copy_sig (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4C525E3: orte_grpcomm_API_allgather (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4C46D09: pmix_server_fencenb_fn (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0xA01B675: ???
==42361== by 0xA05A331: ???
==42361== by 0xA054C4F: ???
==42361== by 0xA05556A: ???
==42361== by 0xA043D21: ???
==42361== by 0x4EFCC10: opal_libevent2022_event_base_loop (event.c:1370)
==42361== by 0xA04197C: ???
==42361== by 0x3D66C07AA0: start_thread (in /lib64/libpthread-2.12.so)
==42361==
==42361== 96 (80 direct, 16 indirect) bytes in 2 blocks are definitely lost in loss record 212 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C2B709: orte_dt_unpack_sig (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4EC8191: opal_dss_unpack_buffer (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x4EC8FDD: opal_dss_unpack (in /usr/local/lib/libopen-pal.so.20.2.0)
==42361== by 0x89E201B: ???
==42361== by 0x4C6D490: orte_rml_base_process_msg (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x4EFCC10: opal_libevent2022_event_base_loop (event.c:1370)
==42361== by 0x404B30: orterun (orterun.c:1071)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 168 bytes in 1 blocks are possibly lost in loss record 246 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x87DECDF: ???
==42361== by 0x4C23637: orte_finalize (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0x404B98: orterun (orterun.c:1089)
==42361== by 0x403455: main (main.c:13)
==42361==
==42361== 14,464 (128 direct, 14,336 indirect) bytes in 2 blocks are definitely lost in loss record 346 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0x4C46C7B: pmix_server_fencenb_fn (in /usr/local/lib/libopen-rte.so.20.1.0)
==42361== by 0xA01B675: ???
==42361== by 0xA05A331: ???
==42361== by 0xA054C4F: ???
==42361== by 0xA05556A: ???
==42361== by 0xA043D21: ???
==42361== by 0x4EFCC10: opal_libevent2022_event_base_loop (event.c:1370)
==42361== by 0xA04197C: ???
==42361== by 0x3D66C07AA0: start_thread (in /lib64/libpthread-2.12.so)
==42361== by 0xAC746FF: ???
==42361==
==42361== 122,881 (176 direct, 122,705 indirect) bytes in 2 blocks are definitely lost in loss record 351 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0xA054BDF: ???
==42361== by 0xA05556A: ???
==42361== by 0xA043D21: ???
==42361== by 0x4EFCC10: opal_libevent2022_event_base_loop (event.c:1370)
==42361== by 0xA04197C: ???
==42361== by 0x3D66C07AA0: start_thread (in /lib64/libpthread-2.12.so)
==42361== by 0xAC746FF: ???
==42361==
==42361== 136,119 bytes in 306 blocks are definitely lost in loss record 352 of 352
==42361== at 0x4A06A2E: malloc (vg_replace_malloc.c:270)
==42361== by 0xA01EA87: ???
==42361== by 0xA0424C8: ???
==42361== by 0xA05EAE2: ???
==42361== by 0xA05F55C: ???
==42361== by 0xA054D18: ???
==42361== by 0xA05556A: ???
==42361== by 0xA043D21: ???
==42361== by 0x4EFCC10: opal_libevent2022_event_base_loop (event.c:1370)
==42361== by 0xA04197C: ???
==42361== by 0x3D66C07AA0: start_thread (in /lib64/libpthread-2.12.so)
==42361== by 0xAC746FF: ???
==42361==
==42361== LEAK SUMMARY:
==42361== definitely lost: 145,701 bytes in 413 blocks
==42361== indirectly lost: 169,449 bytes in 568 blocks
==42361== possibly lost: 2,976 bytes in 24 blocks
==42361== still reachable: 99,889 bytes in 1,003 blocks
==42361== suppressed: 0 bytes in 0 blocks
==42361== Reachable blocks (those to which a pointer was found) are not shown.
==42361== To see them, rerun with: --leak-check=full --show-reachable=yes
==42361==
==42361== For counts of detected and suppressed errors, rerun with: -v
==42361== ERROR SUMMARY: 53 errors from 53 contexts (suppressed: 6 from 6)
And this is some OpenMPI information
Package: Open MPI buildd@lgw01-07 Distribution
Open MPI: 2.0.2 Open MPI repo revision: v2.0.1-348-ge291d0e Open MPI release date: Jan 31, 2017
Open RTE: 2.0.2 Open RTE repo revision: v2.0.1-348-ge291d0e Open RTE release date: Jan 31, 2017
OPAL: 2.0.2
OPAL repo revision: v2.0.1-348-ge291d0e OPAL release date: Jan 31, 2017 MPI API: 3.1.0 Ident string: 2.0.2 Prefix: /usr Configured architecture: x86_64-pc-linux-gnu Configure host: lgw01-07 Configured by: buildd Configured on: Fri Feb 10 11:13:16 UTC 2017 Configure host: lgw01-07 Built by: buildd Built on: Fri Feb 10 11:20:28 UTC 2017 Built host: lgw01-07 C bindings: yes C++ bindings: yes Fort mpif.h: yes (all) Fort use mpi: yes (full: ignore TKR) Fort use mpi size: deprecated-ompi-info-value Fort use mpi_f08: yes Fort mpi_f08 compliance: The mpi_f08 module is available, but due to limitations in the gfortran compiler, does not support the following: array subsections, direct passthru (where possible) to underlying Open MPI's C functionality Fort mpi_f08 subarrays: no Java bindings: yes Wrapper compiler rpath: disabled C compiler: gcc C compiler absolute: /usr/bin/gcc C compiler family name: GNU C compiler version: 6.3.0 C++ compiler: g++ C++ compiler absolute: /usr/bin/g++ Fort compiler: gfortran Fort compiler abs: /usr/bin/gfortran Fort ignore TKR: yes (!GCC$ ATTRIBUTES NO_ARG_CHECK ::)
Thank you.
Accessing all derived children from parent in singleton
I am trying to write a singleton parent class that could be used as a basic accessor for all of its derived children, and getting stuck on wrapping my mind around the logic. I wrote some code, but it doesn't compile :(
Also, I am not sure if I am using the design pattern right either -- maybe I am supposed to use some other one?
Below is the code that I am trying to compile. The main point of the final code is to have a singleton for global configuration, and the children are configuration classes for different parts of the program.
template <struct T>
struct Parent {
T* operator[](std::string child) {
return dynamic_cast<T*>(children_[child]);
}
static const T& getInstance() {
if (!one_parent_to_rule_them_all_)
one_parent_to_rule_them_all_ = new Parent;
return dynamic_cast<T>(*one_parent_to_rule_them_all_);
}
std::string Dump() {
std::string res = "";
for (const auto& child : children_) {
res += child.second->Dump();
}
return res;
}
protected:
Parent() = default;
Parent(std::string child_name, Parent* child) {
children_[child_name] = child;
}
static Parent* one_parent_to_rule_them_all_;
static std::map<std::string, Parent*> children_;
};
struct Child1 : Parent<Child1> {
Child1() : Parent("child1", this);
int foo = 0;
std::string Dump() {
return std::string(foo);
}
};
// More children here!
class ICanHazParentz {
// This class wants to have an instance of the parent,
// without specifying the children
public:
Parent p;
void Dump() {
std::cout << Parent::Dump() << std::endl;
}
}
class ICanHazChild1 {
// This class wants to have access to a child,
// without specifying the parent
public:
void Dump() {
std::cout << Parent::getInstance()["child1"]->Dump() << std::endl;
}
}
int main() {
Child1 c1;
// More children
ICanHazParentz ichp;
ichp.Dump();
}
Although the current code looks silly, it is just an oversimplification of the final code.
Forward declaration mess
I am creating a multithreaded class method that needs to call compute
.
void compute(const Me::MyClass<T>& c1, Me:: MyClass<T>& target,std::size_t start);
namespace Me{
template<typename T> class MyClass{
computeMultiThreaded(){
MyClass<T> target = MyClass();
std::size_t n_threads = std::thread::hardware_concurrency();
std::vector<std::tuple<std::size_t, std::size_t>> parts = split_job(n_threads, number_jobs);
std::vector<std::thread> threads;
for (std::size_t ti = 0; ti < n_threads; ti++)
{
// , parts[ti], minCol, this, m2, returnMatrix));
threads.push_back(std::thread(compute,parts[ti]));
}
}
}
}
void compute(const Me::MyClass<T>& c1, Me:: MyClass<T>& target,std::size_t start){
...
}
Now when I try to compile this with compute
defined after MyClass
, Me::MyClass
is not known in the first definition of compute
. When I delete the first declaration, compute
will not be known when creating the thread?
How can I resolve this catch 22?
error: use of undeclared identifier 'Me'
Why does this code to initialize a string to a single character call the initializer_list constructor?
I was recently working on a C++ project and came across an edge case with the string constructors that I can't fully understand. The relevant code (which you can run here) is as follows:
#include <iostream>
#include <string>
using namespace std;
int main() {
string directParens(1, '*');
string directBraces{1, '*'};
string indirectBraces = {1, '*'};
cout << directParens.size() << endl; // 1
cout << directBraces.size() << endl; // 2
cout << indirectBraces.size() << endl; // 2
return 0;
}
The brace-initialized versions of the strings end up having two characters in them, namely, a char
with numeric value 1 followed by a star.
I don't understand why the brace-initialized versions of the string invoke the initializer_list
constructor rather than the constructor taking in a size and a character. The initializer_list
constructor has this signature:
basic_string(std::initializer_list<CharT> init,
const Allocator& alloc = Allocator());
Given that string
is an alias for basic_string
char, the specific signature would be
string(std::initializer_list<char> init,
const Allocator& alloc = Allocator());
How is the initializer {1, '*'}
, which contains elements both of type int
and of type char
, matching this constructor? I was under the impression that all literals in an std::initializer_list
must have the same type - is that incorrect?
Why did C++11 deprecate the default value in std::vector's fill constructor?
In C++98 the prototype for std::vector
's fill constructor has a default value for the initializer:
explicit vector (size_type n, const value_type& val = value_type(),
const allocator_type& alloc = allocator_type());
In C++11 it becomes two prototypes:
explicit vector (size_type n);
vector (size_type n, const value_type& val,
const allocator_type& alloc = allocator_type());
(In C++14 the fill constructor changed again, but it's not the point of this question.)
My question is, why did C++11 deprecated the default initializer value value_type()
?
BTW: I tried with this code below in clang++ -std=c++11
and it issued an error, which means the value type still need to have a default constructor like S() {}
.
#include <vector>
struct S {
int k;
S(int k) : k(k) {}
};
int main() {
std::vector<S> s(5); // error: no matching constructor
}
How can I call a method from QMainWindow?
I do need to invoke a method from my MainWindow class, that inherit from QMainWindow
class from a class outside MainWindow, something like this:
Q_ASSERT(QMetaObject::invokeMethod(mainWindow, NAMEOF(attachmentDownloadComplete)));
mainWindow
is of class MainWindow : public QMainWindow
type
the error is:
no matching function for call to 'QMetaObject::invokeMethod(MainWindow*&, const char [27])'
Q_ASSERT(QMetaObject::invokeMethod(mainWindow, "attachmentDownloadComplete"));
My question is how can I manage to call invoke this method?
ques. based on factors and multiples
long long i,N=123456789,j,c; // A[n]=0:live,=1:killed or disintegrated
//long long c,N;
int A[N]={0};
for(i=N;i>1;i--)
{
if(A[i]==0)
{
A[i]=1; //kill A[i]
c++;
for(j=1;j<(sqrt(i));j++) //find fac of i & disint. them
{
if(i%j==0)
{
A[j]=1; //disintegrate j
A[i/j]=1; //disintegrate n/j
}
}
}
}cout<<c;
Above code is solution to ques. given here [http://ift.tt/2vDClJB]. Code is working good for small inputs but not for large inputs.What changes should I make?
C++ Cannot convert from Initializer List to std::pair
I have a function called TestFunction which I've simplified down for this question... but in essence, I'm getting an error which says, " cannot convert from 'initializer list' to std::pair". Here's my simplified function:
#include <iostream>
#include <map>
void MyClass::TestFunction(cli::array<int>^ ids){
std::multimap<int, int> mymap;
int count = ids->Length;
for (int i = 0; i < count; ++i) {
//fill in the multimap with the appropriate data key/values
mymap.insert(std::pair<int, int>((int)ids[i], (int)i));
}
}
As you can see, it's a really basic function (when simplified), but I get an error when I try to insert the data into the multimap. Does anyone know why?
One mutex vs Multiple mutexes. Which one is better for the thread pool?
Example here, just want to protect the iData
to ensure only one thread visit it at the same time.
struct myData;
myData iData;
Method 1, mutex inside the call function (multiple mutexes could be created):
void _proceedTest(myData &data)
{
std::mutex mtx;
std::unique_lock<std::mutex> lk(mtx);
modifyData(data);
lk.unlock;
}
int const nMaxThreads = std::thread::hardware_concurrency();
vector<std::thread> threads;
for (int iThread = 0; iThread < nMaxThreads; ++iThread)
{
threads.push_back(std::thread(_proceedTest, iData));
}
for (auto& th : threads) th.join();
Method2, use only one mutex:
void _proceedTest(myData &data, std::mutex &mtx)
{
std::unique_lock<std::mutex> lk(mtx);
modifyData(data);
lk.unlock;
}
std::mutex mtx;
int const nMaxThreads = std::thread::hardware_concurrency();
vector<std::thread> threads;
for (int iThread = 0; iThread < nMaxThreads; ++iThread)
{
threads.push_back(std::thread(_proceedTest, iData, mtx));
}
for (auto& th : threads) th.join();
- I want to make sure that the Method 1 (multiple mutexes) ensures that only one thread can visit the iData at the same time.
- If Method 1 is correct, not sure Method 1 is better of Method 2? Thanks!
Performence issue with UBO
i'm using OpenGL 4.1 (and SFML on Windowing), and recently i begin using the UBO but i've some issues, i do this
static constexpr auto ACCESS_MODE = BitfieldAccessMode::MAP_WRITE_BIT | BitfieldAccessMode::MAP_INVALIDATE_RANGE_BIT;
const auto &projection_matrix = m_cache.matrices[MatrixType::Projection];
const auto &view_matrix = m_cache.matrices[MatrixType::View];
m_cache.transform_uniform_buffer->bind();
TransformBlock *ptr = reinterpret_cast<TransformBlock*>(m_cache.transform_uniform_buffer->mapRange(ACCESS_MODE, 0, sizeof(TransformBlock)));
ptr->projection = projection_matrix.matrix;
ptr->view = view_matrix.matrix;
ptr = nullptr;
m_cache.transform_uniform_buffer->unmap();
m_cache.transform_uniform_buffer->unbind();
but i got 1 fps, this
auto tp = Clock::now();
m_window.display();
auto tp2 = Clock::now();
storm::DLOG("t: %f", std::chrono::duration_cast<std::chrono::milliseconds>(tp2 - tp).count());
[Debug] t: 568
[Debug] t: 1033
[Debug] t: 1006
[Debug] t: 684
Sorry for my english, i've recently started to learn it.
Are there user-defined-literals for variables?
The user-defined-literals from C++11 helps the integers and float numbers have a vertain unit like m,cm,mm,km,and so on. But it seems that it deals only with constant. I have a runtime program which always calculates some lengths and convert them between different units. Are there also similar mechanisms like user-defined-literals in C++ for variables?
C++ can't push class objects into std::vector
I thought i would be used to the usage of a vector. But somehow im getting problems while pushing class Objects into my std::vector.
My vector is declared in my Class : "Galaxy":
//Galaxy.h
#ifndef GALAXIS_H
#define GALAXIS_H
#include "Stern.h"
#include <vector>
class Galaxis {
public:
Galaxis();
Galaxis(const string& datei);
virtual ~Galaxis();
void print()const;
private:
vector<Stern> galaxy;
};
#endif /* GALAXIS_H */
And now i want to use it to hold my "Star" objects. In the constructor
//Galaxy.cpp
Galaxis::Galaxis(const string& datei) {
ifstream ifs;
ifs.open(datei, ios::in);
if (ifs.is_open()) {
Stern star;
while (!ifs.eof()) {
ifs>>star;
this->galaxy.push_back(star);
}
this->print();
ifs.close();
} else {
throw invalid_argument("File '" + datei + "' not Found");
}
}
Now i want to print them with my print() method,
void Galaxis::print() const {
for (int i=0; i < galaxy.size(); i++) {
galaxy[i].print();
}
}
Somehow the output only shows empty "Stern" objects. The streaming operator has been correctly implemented and tested, aswell as the print method for the "Stern" objects. Hope you can help me
C++11 extern complex Container and Container initialization
When we want to have an exported variable (both in C and C++) we need to:
- declare the variable as extern in an hpp header file (i.e. extern int x;)
- initialize the variable in a cpp file (i.e.: int x = 0).
However, I have found difficulties with containers and I am receiving messages like "the variable is declared multiple times" and so forth.
For example:
hpp file:
typedef std::vector<std::pair<std::string, std::string>> VectorOfPairs_t;
export VectorOfPairs_t vectorOfPairs;
cpp file:
std::pair<std::string, std::string> myPair;
myPair = std::make_pair("hello", "world");
vectorOfPairs.push_back( myPair ); // All this is just a hack
// to initialize the container...
main.cpp (or other cpp):
use of vectorOfPairs accordingly to my requirements
But, as I have mentioned, this is not compiling.
Could you please tell me what I am doing wrong?
Error in compilation. what will be the correct code and output?
why is there a compilation error(lvalue required in line 3)
what will be the correct code and then the output?
#include<iostream>
#define PRINT(i,LIMIT) \
do{ if(i++<LIMIT)\
{ cout<<"Gradeup";\
continue; }\
}\
while(1)
using namespace std;
int main() {
PRINT(0,3);
return 0;
}
Is the unique_ptr returned from a function an lvalue?
Lately, I've been doing a little digging into the C++11 std and was playing around with unique_ptrs.
Let's say I have a function which returns a unique_ptr to an integer.
unique_ptr<int> GetUniquePtr(int i)
{
return make_unique<int>(i);
}
In my main function, I am able to take the address of the value returned by the function. This means that the expression must evaluate to an lvalue
int main()
{
cout << &(GetUniquePtr(5));
}
I know if I assign the function call to a unique pointer, the move consturctor of the unique_ptr will be called, treating the returned value as an rvalue reference.
int main()
{
unique_ptr<int> uPtr = GetUniquePtr(5);
}
This dual behaviour of returning unique_ptr kind of confuses me, as I was of the impression that unique_ptr returned from a function call is always evaluated as an rvalue.
Can anyone shed some light on what's actually going on?
No Crash when static member variables are deleted
I have the below code:
#include <iostream>
class A
{
public:
static void* operator new(std::size_t sz) throw();
static void operator delete(void* ptr);
static A obja[2];
static int i;
void show()
{
std::cout << "Called Show" << std::endl;
}
A(const char * where)
{
std::cout << where << std::endl;
}
};
A A::obja[2] = {A("global1"),A("global2")};
int A::i = 0;
static void* A::operator new(std::size_t sz) throw()
{
std::cout << "Called Con " << std::endl;
std::cout << "Addr of " << i << " " << &obja[i] << std::endl;
return &obja[i++];
}
static void A::operator delete(void* ptr)
{
i--;
std::cout << "Called Des" << std::endl;
}
int main()
{
(void)A::obja;
A * a1 = new A("local main");
std::cout << "Addr of a1 " << a1 << std::endl;
a1->show();
A * a2 = new A("local main");
std::cout << "Addr of a2 " << a1 << std::endl;
a1->show();
delete a2;
}
I am purposefully deleting static variable as in code due to some reason - I was expecting that when the program would terminate the global / static variable destruction would happen and an segmentation fault should be observed (cause they are already de-allocated) - but the program terminated successfully:
$ c++ test3.cpp -std=c++11
$ ./a.exe
global1
global2
Called Con
Addr of 0 0x408030
local main
Addr of a1 0x408030
Called Show
Called Con
Addr of 1 0x408031
local main
Addr of a2 0x408030
Called Show
Called Des
Should we not experience a segmentation fault here - is it legitimate?
C++ cin.get(ch) as while loop argument and toupper() method
while (!(cin.get(ch)) || ch >= ('A' + x) || ch < 'A') {}
This are the arguments of while loop and I would like to convert char 'ch' to upper letter, by using toupper() method. Is it possible to use toupper() here without implementing any bigger reconstructions to the code?
dimanche 27 août 2017
Can not capture a random distribution and generator by value in lambda?
The following code works fine
#include <iostream>
#include <random>
int main() {
std::default_random_engine generator;
std::normal_distribution<double> distribution(5.0, 2.0);
std::vector<double> v(100);
std::generate(v.begin(), v.end(), [&] () { return distribution(generator); });
return 0;
}
However, changing the capture list of the lambda to [=]
or [&, distribution]
or [&, generator]
causes
rand.cpp:9:59: error: no matching function for call to object of type 'const std::normal_distribution<double>'
error: assigning to 'double' from incompatible type 'void'
Are there some kinds of objects can not be captured by value in a lambda ?
std::async is blocking the process exit if the thread is created from a dll?
Scenario:
I have a console application (consoleApp
) in which i use an exported function (exported_func
) from another dll. In that function, i have started a new infinite thread. Here is the code -
EXPERIMENTAL_API int exported_func(void)
{
auto f = []() {
while (true)
{
cout << "H";
this_thread::sleep_for(100ms);
}
return 1;
};
async_res.value = async(launch::async, f);
return 1;
}
Now, from the main()
function i have called this function and after that i started an infinite loop in the main function. Here is the code -
int main()
{
exported_func();
while (true)
{
cout << "L";
this_thread::sleep_for(100ms);
}
return 0;
}
Problem:
The problem is that, if i want to close my console application by clicking the close button of the console, it takes 10 seconds to close the application.
And more, if i create a process (for the consoleApp.exe) using CreateChildProcess
, then that process cant be terminated using ExitProcess
.
But if i create the thread (async) from the main function(from consoleApp) then it closes immediately and can be terminated using ExitProcess
.
Can anyone please explain whats happening here?
Catch fails on simple example
I am trying to integrate Catch
unit testing to my project but it fails for the currently available
Catch v1.10.0
Generated: 2017-08-26 15:16:46.676990
Example:
test.cpp
#include "catch.hpp"
#define CATCH_CONFIG_MAIN
TEST_CASE("CATCH TEST"){
REQUIRE(1 == 1);
}
g++ test.cpp -o test.exe -std=c++11
Error:
Undefined symbols for architecture x86_64:
"Catch::ResultBuilder::endExpression(Catch::DecomposedExpression const&)", referenced from:
Catch::BinaryExpression<int const&, (Catch::Internal::Operator)0, int const&>::endExpression() const in test-b77427.o
"Catch::ResultBuilder::setResultType(bool)", referenced from:
Catch::BinaryExpression<int const&, (Catch::Internal::Operator)0, int const&>::endExpression() const in test-b77427.o
"Catch::ResultBuilder::useActiveException(Catch::ResultDisposition::Flags)", referenced from:
____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
"Catch::ResultBuilder::react()", referenced from:
____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
"Catch::ResultBuilder::ResultBuilder(char const*, Catch::SourceLineInfo const&, char const*, Catch::ResultDisposition::Flags, char const*)", referenced from:
____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
"Catch::ResultBuilder::~ResultBuilder()", referenced from:
____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
"Catch::SourceLineInfo::SourceLineInfo(char const*, unsigned long)", referenced from:
____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
___cxx_global_var_init in test-b77427.o
"Catch::isDebuggerActive()", referenced from:
____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
"Catch::AutoReg::AutoReg(void (*)(), Catch::SourceLineInfo const&, Catch::NameAndDesc const&)", referenced from:
___cxx_global_var_init in test-b77427.o
"Catch::AutoReg::~AutoReg()", referenced from:
___cxx_global_var_init in test-b77427.o
"Catch::toString(int)", referenced from:
Catch::ExpressionLhs<int const&>::reconstructExpression(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&) const in test-b77427.o
Catch::BinaryExpression<int const&, (Catch::Internal::Operator)0, int const&>::reconstructExpression(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >&) const in test-b77427.o
"Catch::ResultBuilder::shouldDebugBreak() const", referenced from:
____C_A_T_C_H____T_E_S_T____0() in test-b77427.o
"_main", referenced from:
implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit
g++ --version
Configured with: --prefix=/Applications/http://ift.tt/1d5DwEL --with-gxx-include-dir=/Applications/http://ift.tt/2h6IoD1
Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Applications/http://ift.tt/1z8WHIF