question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
6,403,222 | 6,403,251 | Cross platform Gui library with liberal license | I am looking for a cross platform gui library that can be used to create dialog boxes, that must fit the following requirements:
Be written in C or C++.
Be compatible with at least Windows, Mac and Linux.
Be relatively mature.
Be under a license that does not require Copyright text in the documentation of derivative w... | I'd go with wxwidgets. According to the license it it essentially LGPL with the following exception that applies to your question:
The exception is that you may use, copy, link, modify and distribute
under your own terms, binary object code versions of works based on the
Library.
|
6,403,224 | 6,480,412 | Getting the largest type available | How can I get the name of largest available type in my compiler? Is it possible at all?
Something like:
auto largest = get_largest_type();
and auto in my case would be long long.
| Well, depending on how badly you need this, you can try some serious metaprograming here...
Firstly, you will obviously need some kind of "pack" defining all available primitive types, so here it is:
template<typename... TYPES>
class pack
{};
typedef pack<float, double, long double, unsigned short, unsigned int,
u... |
6,403,329 | 6,403,392 | Referencing next class in template class, gettng error "expected ';'" | I am getting the following when trying to compile the code below:
preallocarray.h: In member function 'void PreallocArray<T>::push_back(const T&)':
preallocarray.h:82: error: expected `;' before 'itr'
I have a nested const_iterator class inside of my LinkedList class I created. It's been many years since I've done C+... | LinkedList<Node>::const_iterator itr; // error occurs here
Based on the fact the enclosing class is actually a class template, I suspect that you intended to write T instead of Node. What is Node by the way? And where is it defined?
If you really wanted to write T, then you've to write it as:
typename LinkedList<T>::... |
6,403,498 | 6,403,538 | Force inclusion of a header in project | I have a header with a particular set of rules that the user must follow. If the user does not want to follow the rules, they must define a preprocessor macro which will disable the checks. If the user is using the library, the user must include the header in every one of their classes that uses any code from the libra... | I'm not sure if I understand your question entirely, but do you think this will help?
BaseHeader.h:
#pragma once
#define BASE_HEADER_INCLUDED
...
internal_header.h:
#pragma once
#ifdef NOT_USING_BASE_HEADER
#ifdef BASE_HEADER_INCLUDED
#error You can't both define NOT_USING_BASE_HEADER and include the base-... |
6,403,620 | 6,403,695 | C++0x: Error with std::function::target and template arguments | I currently write on an event handler system in C++0x. The "handlers" for each event (there can be multiple handlers) are registered by passing any kind of function/method that can be stored in a std::function object. This is done in C# style using the overloaded += operator. My Event-Class looks basically like this (s... | You need to use template keyword as:
HandlerFunctionPtr pt2func = it->template target<HandlerSignature>();
Its because you're calling a function template on an object whose type depends on a template argument. In the absence of the keyword template, the compiler is going to parse your code as,
HandlerFunctionPtr pt2fu... |
6,403,842 | 6,403,871 | is virtual inheritance from pure abstract classes (interfaces) necessary | Why is it that in the code below the compiler complains that PureAbstractBase is an ambiguous base class of MultiplyInheritedClass? I realize I have two copies of the PureAbstractBase in MultiplyInheritedClass and that FirstConreteClass and SecondConreteClass should be derived virtually because they're the middle row ... | You need virtual inheritance to overcome the diamond-ambiguity:
class FirstConcreteClass : public virtual PureAbstractBase { ... };
class SecondConcreteClass : public virtual PureAbstractBase { ... };
Long-winded explanation: Suppose you have this:
// *** Example with errrors! *** //
struct A { virtual int foo(); };... |
6,403,854 | 6,403,934 | How to move the pointer of istream by n characters? | I would like to skip a few characters in a binary file between two istream getlines. What is the best way to do it?
Shell I just read into a dummy variable with istream::read?
Or shell I use n = istream::tellg and istream::seekg = n + 1000?
| You can simply move a stream position relative to the current position by using the std::ios::cur position argument:
std::ifstream f("myfile.txt"); // current position 0
f.seekg(200, std::ios::cur); // relative seek
Negative values are also permitted. See e.g. here.
|
6,404,160 | 6,404,175 | Sort a std::list<myclass*> with myclass::operator<(myclass &other) | I have a std::list<myclass*> and in my class I have myclass::operator<(myclass &other) defined.
I use the std::list.sort() function, but it does not change anything in that list. Maybe it just sorts the pointers?
How can I sort the actual items in that list?
| You are sorting the pointer values, not the myclass values. You have to write your own predicate to compare pointers by dereference:
template <typename T> bool PComp(const T * const & a, const T * const & b)
{
return *a < *b;
}
std::vector<Foo*> myvec;
std::list<Foo*> mylist;
std::sort(myvec.begin(), myvec.end(), P... |
6,404,268 | 6,404,283 | For loop just... not starting? | This is a bizarre problem. I've got a void function that performs a for loop and nothing else, but the for loop doesn't ever start, even though the function is being called. Here is the function:
void Cell::Consolidate()
{
cout << "Consolidating (outside)...\n";
for(int i = 0; i < m_Tiles.size(); ++i)
{
... | i < m_Tiles.size()
This loop condition gets checked on entrance to the loop, not only after each iteration. If your m_Tiles vector is empty, well, no loop for you.
|
6,404,352 | 6,414,219 | C++ Rewrite a file but leaving out everything before a word | I'm using Visual C++ Express 2010... and I'm very new to C++.
I want to read a file then remove everything before the word "<--START-->" and rewrite the file with the rest.
Here's the code I've got for reading the file so far:
#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
int main() ... | You cannot read a file then remove everything before the word "<--START-->" and rewrite the file with the rest, except in memory as answered by Benjamin. Otherwise you need an intermediate file. In all cases you should handle various error conditions. This should do it:
#include <iostream>
#include <fstream>
#include <... |
6,404,473 | 6,404,490 | How to end a whole program | I have a pretty simple C++ console program. It's working fine, but I have some issues.
I have 2 functions. First function called "input" asks from user to input numbers from 6 to 10. In that function I declared:
if ((a[i][j] < 6) || (a[i][j] > 10))
{
cout<<"Invalid input!";
return 0;
}
Second function called... | if(input(matrix,number) != 0) output(matrix,number);
// You don't {} for a single instruction
This should fix your problem.
|
6,404,586 | 6,404,634 | Double to Const Char* | How can I convert a double into a const char, and then convert it back into a double?
I'm wanting to convert the double to a string, to write it to a file via fputs, and then when I read the file, it will need to be converted back into a double.
I'm using Visual C++ 2010 Express Edition.
| If you just want to write the double values to file, you can simply write it, without converting them into const char*. Converting them into const char* is overkill.
Just use std::ofstream as:
std::ofstream file("output.txt")'
double d = 1.989089;
file << d ; // d goes to the file!
file.close(); //done!
|
6,404,636 | 6,405,064 | libstdc++-6.dll not found | I have been working on a project (a game to be specific) and I feel that I should start over with different libraries. So when doing this I reinstalled Code::Blocks and setup my new libraries and includes.
But as of now Im having a problem starting u[ my new project to test if all of the includes work. This problem is... | If you are using MingW to compile C++ code on Windows, you may like to add the options -static-libgcc and -static-libstdc++ to link the C and C++ standard libraries statically and thus remove the need to carry around any separate copies of those. Version management of libraries is a pain in Windows, so I've found this ... |
6,404,856 | 6,404,886 | Generic function to flatten a container of containers | I am trying to get a better hold on iterators and generic functions. I thought it would be a useful exercise to write a function that converts container1 < container2 <type> > to container3 <type>. For example, it should be able to convert vector< deque<int> > to list<int>.
I figured all the container access should b... | I found the issue. Thanks to SFINAE (Substitution failure is not an error) your compiler couldn't find the correct template because you are trying to call operator() on start by typing start() (probably a typo). Try this:
#include <iterator>
#include <algorithm>
// COCiter == Container of Containers Iterator
// Oiter ... |
6,404,864 | 6,404,883 | Arrays of objects in C++ | So, I'm trying to declare classes in an array, but I'm not sure how to do it. Here is the code I have, but my declaring the classes is not working. I'm sure that my syntax is wrong, but what should I do?
class Menu{
public:
Menu(int j, int k){
//some code
}
};
Menu allMenus[2] = {
(1, 7),
(2, 9)
};... | Try:
Menu allMenus[2] = {
Menu(1,7),
Menu(2,9)
};
|
6,404,871 | 6,404,891 | what is the default file extension of c++0x source files? | when we was programming C file extensions were usually "C" or "CC" or "H" based. then we migrated to C++ and new file extensions were introduced "cpp" and "hpp" although "hpp" is not commonly used (or at least I think so), so what is new C++0x file extensions or how do they differ from c/c++ files?
| C++0x is just a new standard for C++, not a new language. There's no need to change the file extension and I don't believe anyone will.
|
6,404,945 | 6,404,968 | C++ template type which has a specific member method | What is a good way to call a member function of template type? Will the below foo() code only compile for types that have the bla() function defined?
class A { void bla(); };
template<typename T>
void foo() {
T t;
t.bla();
}
int main() {
foo<A>();
return 0;
}
Can I use boost::enable_if to only define... | For every type you try to invoke the foo function with, the compiler will generate a new foo function with the given it and compile, if you can compile the foo function with a given type, it will works.
So in your case, the foo function will work with every type that have a bla function and that have a default constru... |
6,405,137 | 6,405,144 | asc and chr equivalent in C/C++ | Well the title pretty much sums it up. I want to use something like asc("0") in C++, and want to make the program platform independent so don't want to use 48! Any help appreciated.
| You can simply use single-quotes to make a character constant:
char c = 'a';
The character type is a numeric type, so there is no real need for asc and chr equivalents.
Here's a small example that prints out the character values of a string:
#include <stdio.h>
int main(int argc, char **argv) {
char str[] ="Hello, W... |
6,405,196 | 6,405,286 | Cannot link to a library no way...VS 2010 lib | I can successfuly build and use a library. The later only if both the library and the other project is in the same solution....
I copied the isam.lib isam.dll isam.exp isam.h under a folder called lib...
Then i created a new solution..
Set linker -> Input to use my isam.lib ... Building fails, cant find that file...... | Well, let's assume you told the linker to link to isam.lib with the Linker, Input, Additional Dependencies setting. Then the possible cause of the linker error is that you wrote the isam code in C and you are using it in a C++ program. You have to tell the compiler that the code was written in C:
#include "stdafx.h"
... |
6,405,212 | 6,405,216 | Does C# use the -> pointer notation? | I am trying to learn C# and I am familiar with the C++ struct pointing notation ->. I was curious if that crossed over into C#.
Example:
someStruct->someAttribute += 1;
| There is pointer notation in C#, but only in special cases, using the unsafe keyword.
Regular objects are dereferenced using ., but if you want to write fast code, you can pin data (to avoid the garbage collector moving stuff around) and thus "safely" use pointer arithmetic, and then you might need ->.
See Pointer typ... |
6,405,315 | 6,405,374 | Pthread instance variable running methods from class | I am trying to design an active object of sorts that once created, essentially runs in its own thread. What I have done so far is create a class that contains a pthread instance variable, and then in the constructor for that class, it should send the pthread on its way.
Since pthread_create() takes a function parameter... | Your compilation problem is likely that run is defined in your implementation file after you reference it in your constructor. Either move the definition of run before the constructor or insert a declaration of run before the constructor.
As for your problem making it a class member that won't work as pthread_create is... |
6,405,454 | 6,405,472 | When to delete[] a pointer c++? | I've been toying with c++ for a little while, and coming from java one of the most confusing aspects for me is memory management. For example, lets say I have a method, and in that method I declare a pointer to an object, i want to set that pointer to an attribute of another object using a get method:
SubObject *mySubO... | Tracking memory management can be a burden, the best advice is to avoid it in as much as possible and make it explicit by avoiding raw pointers. If you only need temporary access to a variable that is held somewhere else (in your example, it is a member of a different object, and thus managed there) you should not dele... |
6,405,767 | 6,405,885 | protocol buffer lite versus regular protocol buffer | I've been investigating c++ serialization frameworks will small footprint and good performance. I've found this thread
c++ network serialization
which basically suggest to use the lite version of protocol buffers. It is not clear from this page what are the specific features of the lite version
my question is; what fea... | The "lite" version is not able to serialize to or from iostream, or "FileDescriptor", and it cannot use the Reflection feature (although it does use refection), and... a scattering of other features.
My advice is to just use the lite version until you come across a feature that requires the full version. It is very eas... |
6,406,258 | 6,406,289 | Multiple Class Dependencies | I am trying to make a class that contains two other objects, and those object should maintain a pointer to the class they are contained in. For
For example... (I am only using on object instance variable, in the final imagine there is a class very similar to ClassB)
This is just my main.cpp, figured I would include it... | Add
class ClassA;
before ClassB definition;
Simple example:
class B;
class A {
B * b;
};
class B {
A * a;
};
int main(int argc, char ** argv) {
return 0;
}
|
6,406,307 | 6,406,330 | how do I set a debug mode in c++ | I would like to set a debug mode so that it prints the log statements only if the debug mode is on. For example if I have code like this
printf("something \n");
.
.
.
perror("something \n");
It only works if the debug flag is on.. I don't want to use "if" statements.
I think there is a clever way to do this using #def... | Without going in to specific libraries or solutions, generally people make a logger class or function, and a single debug flag. The debug function checks this flag before calling printf or cout. Then in the rest of your code you simply call your debug function / method.
Here's an example:
class MyDebugger
{
private... |
6,406,356 | 6,406,411 | How to write vector values to a file | I have a large vector.
The ways that I use multiply the run-time of the program hugely. The first is write all values to a string as they are calculated using stringstreams and later write the string to a file. The other method is to make a long string after the fact and write that to the file. However, both of these ... | Using std::ofstream, std::ostream_iterator and std::copy() is the usual way to do this. Here is an example with std::strings using C++98 syntax (the question was asked pre-C++11):
#include <fstream>
#include <iterator>
#include <string>
#include <vector>
int main()
{
std::vector<std::string> example;
example.p... |
6,406,361 | 6,406,457 | LuaBind bindings for c standard library? | I've begun running into slight issues with certain functions that I've bound to lua using luabind. These functions return or take std:string objects as arguments, and the data that c++ eventually gets is garbage, apparently because lua doesn't recognize the datatype. I'm fine with manually binding std:: classes over ... | Luabind already has automatic conversions between Lua strings and std::string (as well as char*). So you should be able to use them as parameters and/or return values just fine. If you are unable to do so, then something is going wrong, either on your side or on Luabind's side.
Luabind also has an adapter to convert a ... |
6,406,475 | 6,406,533 | c++ reference to a vector issues? | Im having some difficulties when passing a reference to a vector as an argument. Initially it was a pointer to a vector of pointers, and the functions called would change attributes of whatever obejct was calling it. For example I used:
(*myVector)[i]->myFunction();
and everything worked perfectly. myFunction() would ... | Hold on a minute. When you changed this snippet:
(*myVector)[i]->myFunction()
To this:
myVector[i].myFunction()
You've actually changed two things:
myVector went from pointer to reference;
The type of the elements inside myVector went from pointer to simple value type.
If you changed the type of the elements to a s... |
6,406,502 | 6,406,610 | Parameter passing in Visual Studio and GCC | Parameter passing in Visual Studio. Note how __m128 types are passed. Does it mean that no more than 4 __m128 arguments should be passed by value.
void good_function(__m128, __m128, __m128, __m128, __m128&);
void bad_function(__m128, __m128, __m128, __m128, __m128);
Does the same rule apply to GCC?
Thank you!
EDIT: I... | The parameter passing description you linked to is actually a x86_64 Windows ABI (application binary interface) description demonstrating how values will be passed to a function at the assembly level (i.e., how the compiler will translate a C-function call to assembly). That being said, the first four arguments will b... |
6,406,567 | 6,406,607 | Getting a pointer to a variable in a union | I was just wondering if this is the correct syntax for a pointer to a char in a union:
union myunion {
char character[4];
}
... = &(myunion.character[0])
It seems to produce the correct result in my application and I can't seem to find the correct syntax on the internet.
Thanks for your help.
| It's the correct syntax. There's one gotcha you need to be aware of, however: x86 processors are little-endian. That means that if you deploy on an x86 platform (which is kinda likely) or any other little-endian platform, and have an integer such that:
int value = 0x01020304;
Then, your char array will read as follow:... |
6,406,578 | 6,407,247 | passing a complex object in c++ to c# through COM | This question expands on the existing question here:
Passing an object from C++ to C# though COM
The previous question deals with a simple object, but I would like to do the same for a complex object.
So instead of TestEntity1 having a single property, if it has another property of type TestEntity2, how can I assign th... | I figured this out myself. :)
I had to use the interface to define the property like this:
[ComVisible(true)]
public interface ITestEntity1
{
string Name { get; set; }
ITestEntity2 Entity2 { get; set; }
}
[ComVisible(true)]
public class TestEntity1 : ITestEntity1
{
public string Name { get; set; }
publ... |
6,406,593 | 6,406,618 | How to get more colors out of C++/Ncurses | How do I get more than the 7 preset colors using the NCurses library with C++?
| If the colors terminfo capability returns 8, then you can't. If it returns a value higher than that then examine the result of the cc capability to see if you can change them via the initc capability.
|
6,406,780 | 6,406,794 | Can one stop using a namespace within one's code? |
Possible Duplicate:
How can I “unuse” a namespace?
After declaring "using namespace mynamespace", for example, is it possible to stop using that namespace mid-code?
Thanks for your help.
| Take a look at the C++ documentation on Namespaces.
http://www.cplusplus.com/doc/tutorial/namespaces/
You can declare that you are 'using' a namespace for a specific scope (such as a function). But I don't believe you can arbitrarily specify where a using statement starts and ends, it is always for the rest of the sco... |
6,406,889 | 6,406,908 | Function argument, const char **, Temp Variable | I want to pass an argument to a function, which takes a const char **
#include<iostream>
using namespace std;
void testFunc(const char **test){}
string testString = "This is a test string";
int main()
{
const char *tempC = testString.c_str();
testFunc(&tempC);
return 0;
}
This code works fine, But I... |
I want to pass testString.c_str() directly.
You can't. std::string::c_str() returns a const char *. In order to make a pointer to a string, you have to put it in a variable and take its address.
That being said, I'm far more concerned about what function you're trying to pass this to. In general, a function that take... |
6,407,662 | 6,407,737 | C++ code meaning and conversion in Java | I have in C++
char *s, mask;
// Some code
If(*s == 0){ //Some more code}
If(*s & mask){ //Some code}
In Java can I write this like
byte s,mask;
//Some code
If(s == (byte)0x0){ //Some more code}
If((s & mask) != (byte)0x0){ //Some Code}
Is the java code correct?
| Does the C++ code really say if (*s == 0), or does it really say if (s == 0)? In the first, you're checking if what s points to is 0, while in the second, you're checking if s is a null pointer. Those are two very different things.
Java doesn't have pointers, so this code cannot be translated to Java directly.
|
6,407,691 | 6,407,710 | Friend declaration in C++ - difference between public and private | Is there a difference between declaring a friend function/class as private or public? I can't seem to find anything about this online.
I mean the difference between:
class A
{
public:
friend class B;
};
and
class A
{
private: //or nothing as the default is private
friend class B;
};
Is there a differ... | No, there's no difference - you just tell that class B is a friend of class A and now can access its private and protected members, that's all.
|
6,407,814 | 6,408,104 | stoi - issue with design | I've asked in one of my posts a question about alternative to boost::lexical_cast and amongst many replies I've got one suggestion stoi as a viable alternative.
I've decided to test it and to my surprise as a second argument to this function (argument describing size) is a pointer to size_t type, not actual size_t type... | That is a way of having optional arguments. Basically, if you are interested in knowing which is the first character that was not converted into the number. If you are not really interested in that result, you can pass nullptr.
§21.5 [string.conversions]/1 [...] If the function does not throw an exception and idx != 0... |
6,408,117 | 6,408,340 | Using cin >> to error handle | I came across this in my readings...
while(!(std::cin >> array[i]))
{
std::cin.clear();
while(std::cin.get()!= '\n')
continue;
std::cout << "enter a new input: ";
}
And, I don't really understand how the error handling is working. std::cin.clear() is used but the code continues to get characters from the cin objec... | what cin.clear() does is to clear the cin stream's error flags.When it does this cin stream operations can continue.the next line extracts a character from the stream and returns it.
To understand what the loop does consider the following case :
Suppose the array is of type int and you enter:abc and then press enter.
c... |
6,408,153 | 6,408,182 | Best data type to store the values like 21.6.7.1 in C/C++ | In 21.6.7.1, 21 represents the some segment, 6 represents some lane inside that segment and so on and so forth. The individual values need to be extracted.
One way to represent this is string, any other way which is better and more convenient than string?
| A structure with a four fields? An array of 4 elements, can also be an option.
|
6,408,183 | 6,408,230 | Is main() overloaded in C++? | 2 valid versions of main() exist in C++:
int main() // version 1
int main(int argc, char **argv) // version 2
But both overloads cannot coexist at the same time. Why not? (Potential use case: while running the program from the terminal, if no arguments are passed the first version is called, otherwise the second ver... | §3.6.1/2 (C++03) says
An implementation shall not predefine
the main function. This function shall
not be overloaded. It shall have a
return type of type int, but otherwise
its type is implementation-defined.
All implementations shall allow both
of the following definitions of main:
int main() { /* ..... |
6,408,198 | 7,515,010 | Bullet vs Newton Game Dynamics vs ODE physics engines | I am trying to pick a physics engine for a simple software application. It would be to simulate a rather small number of objects so performance isn't a huge concern. I am mostly concerned with the accuracy of the motion involved. I would also like the engine to be cross-platform between windows/linux/mac and usable ... | There is a nice comparison of ODE and Bullet here:
http://blog.wolfire.com/2010/03/Comparing-ODE-and-Bullet
Hope it can be useful in making a choice.
|
6,408,268 | 6,408,373 | Call a function concurrently on separate thread | I am working on a network programming and I have created a thread pool. It basically has a queue with mutex lock and condition variable and 5 child threads compete to get a work from the queue. It seems like working correctly with locking and unlocking with the condition variable.
But the problems is that if I call a ... |
the problem is that if I call a
function from the child thread then
only one thread is allowed work
If you base this assumption on your printf, then you are wrong. It's possible that working thread finishes it's work before new item is placed in queue. This creates possibility, that same function will pick up two... |
6,408,481 | 6,416,813 | Access QWizardPage created by Qt Designer | I am using Qt Designer to create a QWizardPage.
I have imported the file into Qt Creator and it runs fine so far (I can build the project and run the wizard just fine)
Now I need to reimplement the isComplete function but I an unable to understand how to do it. The pages are named wizardPage{,1,2_1,_2}. I would like ... | In order to overload the isComplete() function of a QWizardPage, you need to create the QWizardPage yourself. Basically, layout a form -- like you would a dialog -- for only the page you want. Create a class for that page. This class inherits from QWizardPage and reimplements isComplete() for whatever checks you des... |
6,408,569 | 6,408,676 | Blowfish encrypting/decrypting with only first char of key | I'm using Bruce Schneier' source code to encrypt some data using Blowfish. It all seems to work well except that I noticed that when I encrypt with an 8 byte key, it can be decrypted with the first character of that 8 byte key (e.g. encrypt with key "abcdefgh", and can be decrypted with "a").
Here are some extracts fro... | Links to source code I can find for blowfish tend to indicate that the InitializeBlowfish function is defined something like:
int InitializeBlowfish(char *key, size_t len)
and may be called with e.g.:
InitializeBlowfish(key_string_blowfish, strlen(key_string_blowfish));
Rather than, in your case, where you're indicat... |
6,408,573 | 6,408,591 | How to spawn huge numbers of sprites in minimal lines of code | Hey so I was working on my pong game and found it quite tedious to design a new sprite ball everytime i wanted to spawn one ase i ended up being very repetative:
sf::Image img;
img.Create(30,50,sf::Color(255,0,0));
mySprite box(img, sf::Vector2f(0,300), sf::Vector2f(1,1), 0, 36, 300); //TODO: make collision wor... | You can't randomly generate variable names. How would you reference them in your code?
Why don't you just use a vector to store your images and boxes, and then use a loop to spawn sprites:
std::vector<mySprite> boxes;
std::vector<Parameters> parameters;
for(std::vector<Parameters>::iterator it = parameters.begin();
... |
6,408,701 | 6,408,794 | Dynamic Memory Allocation | I have a small confusion in the dynamic memory allocation concept.
If we declare a pointer say a char pointer, we need to allocate adequate memory space.
char* str = (char*)malloc(20*sizeof(char));
str = "This is a string";
But this will also work.
char* str = "This is a string";
So in which case we have to allocate ... | String literals are a special case in the language. Let's look closer at your code to understand this better:
First, you allocate a buffer in memory, and assign the address of that memory to str:
char* str = (char*)malloc(20*sizeof(char));
Then, you assign a string literal to str. This will overwrite what str held pre... |
6,408,752 | 6,408,821 | gdb equivalent for VC++ cl compiler? | I am in the process of porting my application from "MinGW/GCC/make" to "cl compiler/nmake" chain tool.
I extensively used "gdb" for debugging in Linux/MinGW environments.
What is the command-line tool for debugging applications compiled with "cl compiler" ?
| That would be CDB(although I never used it).
But you should take a look at windbg. The tool is bundled with the platform SDK and is IMHO the best debugger for the windows platform.
|
6,408,881 | 6,408,992 | Is it possible to change this code in order to avoid the use of the C++ lambda expression? | I have this code and I would like to know if I can change it in order to avoid the use of the lambda expression:
#include <vector>
#include <algorithm>
#include <iterator>
class B
{
public:
B( double b ):b_(b){}
double b_;
};
class A
{
public:
double error( const B& b ) const {return a_-b.b_;};
double... | In this case, an equivalent functor is:
struct CallError {
A &a;
CallError(A &a) : a(a) {}
double operator()(const B &b) { return a.error(b); }
};
Then:
std::transform( bs.begin(), bs.end(),
std::back_inserter( ds ),
CallError(a));
Note that anything captured by the lambda... |
6,408,932 | 6,408,984 | how to format out in c++? | I know how to use printf() to format output of float, for example:
float i = 1;
printf("%.2f", i);
but how to format the output using cout to output 2 digits after "."?
| Following will do:
std::cout<<std::fixed<<std::setprecision(2)<<i;
You will also need to include iomanip
|
6,409,055 | 6,409,384 | Program execution time | Is there a software/website where I can submit my C, C++ and Java codes and get statistics like the program execution time, memory used ? I'm interested in doing a comparision of the same code in different languages and getting an estimate of which data structures/operations are better suited for which language.
| You can paste your program at ideone and it will tell you the execution time and memory consumption.
|
6,409,127 | 6,409,149 | Can pointers be safely and portably used as object IDs? | Suppose I have a bunch of valid pointers to instances of a class A. Can I safely and portably assume that the pointers will stay the same during the whole object lifetime? In other words, can I use a pointer to an object as a unique object ID?
| Sure; I don't see why not.
A memory address is pretty much the definition of object identity (taking type out of the equation for a moment).
|
6,409,416 | 6,409,499 | fstream save file and file system cross-linked files | Is there a good way to ensure file content is the same you write if your file system have a lot of cross-linked files.
Problem is when i write file content close file and reopen it file corrupted with some other lines from other files. So if i write "AAA" in the file, next time i open file i got: "AAABBBsome stuff".
Co... | There's nothing you can do programmaticly that would help, either create a new file, or ensure that you don't have any cross-linked files (recommended, really, fix your file system)
|
6,409,532 | 6,409,581 | Data structure question |
You are going to write a computer program where the requirement of the data collection is that it should be kept in order and there will be a great deal of adding and deleting from the collection. What data structure would be best to model this?
I was thinking vector, but that's not ordered. Any suggestions? I'm sure... | The classic answer to that is: a Tree. Simplest would be a binary search tree but you also might want to look for Red-Black trees or AVL trees. The boost graph library might also be a good starting point.
|
6,409,759 | 6,495,286 | Extracting segments from a list of 8-connected pixels | Current situation: I'm trying to extract segments from an image. Thanks to openCV's findContours() method, I now have a list of 8-connected point for every contours. However, these lists are not directly usable, because they contain a lot of duplicates.
The problem: Given a list of 8-connected points, which can contain... | Using Mathematica 8, I created a morphological graph from the list of white pixels in the image. It is working fine on your first image:
Create the morphological graph:
graph = MorphologicalGraph[binaryimage];
Then you can query the graph properties that are of interest to you.
This gives the names of the vertex in ... |
6,409,887 | 6,409,951 | Change location where .obj, .exe files are generated in visual studio | How do I change the location where .obj, .exe files are generated in visual studio?
I want these files to always be in a folder on the desktop
| In the project properties, under Configuration Properties, you can set the Output directory and the intermediate directory.
|
6,409,953 | 6,410,006 | Recursively unhide base class members | I try to write a class that takes a tuple of functions as its argument and overloads operator() for all argument_types of the function. Right now this looks like this:
template<typename T>
struct holder {
T t;
};
template<typename T, std::size_t i>
struct overload_helper : public holder<T>, public overload_helper<T,... | using overload_helper<T, i - 1>::operator() in each overload_helper should do the job, so long they aren't ambiguous.
|
6,410,024 | 6,410,223 | Java Classes versus C++ Classes | I just started learning to develop for the Android, and I come from a strictly C++ background. I found that Java does not support Multiple Inheritance, but do we really have to create a seperate .java file for every new Activity?
I have a TabActivity, with 3 more Activitys that make up the tabs. I want to create a List... | The other answers give good points about interfaces and that is probably more what you are looking for. However, for further information, no you don't have to create a new .java file for every new class, there are alternatives. However, keep in mind that more classes is not necessarily a bad thing. Your options are.... |
6,410,333 | 6,410,355 | Overloading unary operator & | Let's consider a class with overloaded unary operator & (Address-of). Let it be class A
template <class C>
class A
{
public:
C * operator &()
{
return &data;
}
//...
private:
C data;
}
Now I want to pass to some function a pointer of type A to fill its data. Let us call it f
void f(A * aut... | Use std::addressof function(or boost::addressof pre C++11). In any case, overloading unary & is highly dubious. Why do it instead of having a named function that returns the address of your data?
|
6,410,916 | 6,411,001 | How do I make a function thread safe in C++? | Let's say I have a thread pool that has 5 child threads. And they are calling a function called "functionA()" How do I make the function to be thread safe?
Also if those 5 threads are called at the same time then are they executed concurrently?
or do they wait until a thread that currently works in the function to be... | A function is already thread safe if it doesn't modify non-local memory and it doesn't call any function that does. In this (trivial) case, you don't have to do anything.
You really want to think about protecting data, not functions. For example, let's say that the function modifies non-local data structure X. Provide ... |
6,411,068 | 6,411,260 | Allocate object in shared memory | It might be a silly question but... I have two processes P1 and P2. Can P1 allocate easily an object O in a shared memory that would be seen for P2? (P1 passes to P2 a pointer to O using a pipe). Something like:
// P1
ptr1 = new SharedMemoryObject(); // object O
pipe.send(ptr1)
// P2
ptr = pipe.recieve()
// I have acc... | Each process has its own address space which means that although a physical memory address may be shared between the two processes, this probably will correspond to different addresses in each process's address space. This means that when designing object that will exist in shared memory you MUST ensure they use offset... |
6,411,270 | 6,411,703 | What does the [[carries_dependency]] attribute mean? | Can someone explain it in a language that mere mortals understand?
| [[carries_dependency]] is used to allow dependencies to be carried across function calls. This potentially allows the compiler to generate better code when used with std::memory_order_consume for transferring values between threads on platforms with weakly-ordered architectures such as IBM's POWER architecture.
In part... |
6,411,368 | 6,411,426 | Errors on whitespace? | So I am trying to compile a set of C files written by someone else, and I am continually getting the following error:
TBin.h:10: error: expected '=', ',',
';', 'asm' or 'attribute' before
'TBin'
This is occurring in a .h file, which currently has a #ifndef and #define before the class definition. The line itself ... | You can't use "class" in C. Try a C++ compiler. ;-)
Just for comparison, here's the output from clang:
% ~/ellcc/bin/ecc ~/test.c
/home/rich/test.c:1:1: error: unknown type name 'class'
class TBin {
^
/home/rich/test.c:1:11: error: expected ';' after top level declarator
class T... |
6,411,411 | 6,411,700 | unable to post a ZIP file to a server using wininet | I am opening file in binary mode using
fopen("abhi.zip","rb");
and reading contents from it and appending it to header.
as there are many null characters in "abhi.zip"(zipped file)
It is posting data only till it reads a null character.
i am using httpsendrequest(...);
i am struck here,can anyone please help me...
| You are not supposed to stick your POST data into the headers, instead, pass it as the lpOptional parameter, passing its length in dwOptionalLength. You will likely need to encode and wrap your data with the proper MIME boundaries (I could find no clear documentation on whether or not this is needed)
|
6,411,476 | 6,411,593 | OpenCV Mat::operator= - does it support copy on write? | From the OpenCV documentation, it appears that copying a matrix is done using a shallow copy, but when changing one of the copies, a copy is done.
The exact reference is:
Mat& Mat::operator = (const Mat& m)
Mat& Mat::operator = (const MatExpr_Base& expr)
Mat& operator = (const Scalar& s)
Matrix assignment operators... | It seems you misunderstood. "Before assigning new data, the old data is dereferenced via Mat::release" does not mean that when you write on a or b then a copy occurs. It means that when you type b=a, you lose the data that was in b.
Long story short : copy on write is not supported.
|
6,411,582 | 6,411,648 | C++ returning pointer from function. Values are lost | I have the the following:
void Class1::method()
{
QStringList* file_list;
collect_file_paths(file_list); //Sends pointer to the method below
}
void Class1::collect_file_paths(QStringList* file_list)
{
//Gather file paths
DirectorySearch ds;
connect(&ds, SIGNAL(updateStatus(QString)), this, SLOT(onStatusUp... | When you do file_list = ds.get_file_names(_strPath); //Returns a pointer of QStringList
you are changing the value of the file_list (a 32/64b memory location) NOT the value of the data that memory location represents.
You need to pass a reference to your pointer (or a pointer to a pointer)
void Class1::method()
{
Q... |
6,411,740 | 6,427,814 | What's the meaning of boost::asio::placeholders::bytes_transferred | What is the meaning of boost::asio::placeholders::bytes_transferred in async_read_until()? In the callback function it returns smaller value, than streambuf.size(). streambuf was clear before the callback. To sum up,...bytes_transferred is not the actual number of bytes went through the socket, but less. Do I have misu... | Resolved. I was passing std::string object to boost::asio::buffer(), instead of std::string.c_str() when sending the reply from the server.
|
6,411,796 | 6,411,824 | what is this syntax mean? operator overloading & throw exception | Saw piece of code in book:
T& operator[](int i) throw(RangeError)
{
if(i >= 0 && i < sz) return ptr[i];
throw RangeError();
}
what does the throw(RangeError) mean? Behind a function declaration, I know we can append const, or =0 (for pure virtual), but I have never seen throw(...)
| It is an exception-specification. It means that your function tells everyone that it has a limited list of things it can throw. Unfortunately or not, but nothing prevents you actually throwing anything else from the function, but if something unexpected is thrown at runtime, then unexpected() will be called. Exception ... |
6,412,042 | 6,412,094 | In c++ code, what do the following keywords mean? SIGSELECT, U32, U16, U8 | I have a question about keyword usage in a c++ struct.
I have seen a struct defined like this:
typedef struct {
SIGSELECT signo;
U32 id;
U32 re;
U16 id1;
U8 id2;
}First;
Please help me understand these keywords: SIGSELECT,U32,U16,U8
| What they "mean" is a quite deep question, and also depends on the environment you are in.
Those are type names, but not standard C++ types so they're not universally known.
A guess would be that the Uxx types are "unsigned integers", of the specified bit widths. So U32 would be a 32-bit unsigned integer, what is known... |
6,412,065 | 6,412,204 | What is the return type of boost::bind? | I want to save the "binder" of a function to a variable, to use it repetitively in the following code by exploiting its operator overloading facilities. Here is the code that actually does what I want:
#include <boost/bind.hpp>
#include <vector>
#include <algorithm>
#include <iostream>
class X
{
int n;
... | The short answer is: you don't need to know (implementation defined).
It is a bind expression (std::tr1::is_bind_expression<T>::value yields true for the actual type).
Look at
std::tr1::function<>
BOOST_AUTO()
c++0x 'auto' keywords (Type Inference)
it's close cousing decltype() can help you move further
1.
std::t... |
6,412,217 | 6,412,294 | Debugging Visual Studio linker | I am trying to build an xll addin for Excel using appropriate framwork downloaded from MS website. I am getting the following linker errors:
1>FRAMEWRK.obj : error LNK2001: unresolved external symbol _Excel4
1>FRAMEWRK.obj : error LNK2001: unresolved external symbol _Excel4v@16
I think that these should be defined in ... | In your project properties, Under Configuration Properties->Linker->Input, you will see 'Additional Dependencies' - these are the files the linker is using. Assuming that _Excel4 and _Excel4v are defined in XLCALL32.LIB (which I think they are), you simply need to ensure that this file is specified in this list.
|
6,412,574 | 6,412,943 | C++ how to generalize class function parameter to handle many types of function pointers? | I do not know if what I am asking is doable, stupid or simple.
I've only recently started dwelling in template functions and classes, and I was wondering if the following scenario is possible:
A class which holds a function pointer to be called. The function pointer cannot be specific, but abstract, so that whenever th... | If you can use C++0x and variadic templates, you can achieve this by using combination of std::function, std::bind and perfect forwarding:
#include <iostream>
#include <functional>
template <typename Result = void>
class instruction
{
public:
template <typename Func, typename... Args>
instruction(Func... |
6,412,587 | 6,412,612 | C++ structures and constructors | A quick question about structures in C++ that I haven't managed to find the answer for:
I've read that the only difference between structures and classes is the member-visibility. So, does the compiler give the structure a default constructor? (and a default copyconstructor, destructor, and assignment operator aswell?)... | Yes, it does, and yes, you can.
|
6,412,706 | 6,413,348 | Multiple CRTs giving segfault | Background: I'm building a plugin for a large simulation framework. I'm compiling a DLL using Visual Studio C++ 2010.
After much bughunting and googling I believe I have a problem which stems from having multiple versions of CRT linked to my DLL. I'm getting a segfault in tidtable.c (from msvcr100.dll), in the function... | You are linking to the release runtime from Visual Studio 2008 and debug runtime of Visual Studio 2010 ... you shouldn't mix and match release and debug in general. If you need the debug VC9 you'll need to install Visual Studio 2008 (install before 2010 to be safe)
However I'd probably just rebuild all projects and de... |
6,412,724 | 6,412,756 | Bspline should be redrawn, without deleting all of the rest of the window | In my mousefunc i call a function bspline. It works like this:
With your mouse you can put controllpoints and according to these points the bspline is drawn.So if you have drawn three points a curve between those points is displayed. By adding another point the old curve disappears and a new one appears. This new one l... | In OpenGL the usual approach is to rerender the whole scene whenever some part of it changes. In your case changing the control points of the B-Spline should trigger a redisplay of the scene instead of perform drawing operations in the mouseclick handler function.
OpenGL has no geometry persistency, it just draws primi... |
6,412,729 | 6,412,786 | Testing C++ code for endian-independence | How can I test or check C++ code for endian-independence? It's already implemented, I would just like to verify that it works on both little- and big-endian platforms.
I could write unit tests and run them on the target platforms, but I don't have the hardware. Perhaps emulators?
Are there compile time checks that can ... | If you have access to an x86-based Mac then you can take advantage of the fact that Mac OS X has PowerPC emulation built in as well as developer tool support for both x86 (little endian) and PowerPC (big endian). This enables you to compile and run a big and little endian executable on the same platform, e.g.
$ gcc -ar... |
6,413,125 | 6,413,397 | C++ pointer and stack memory management | I have a General question about memory management in my c++ code. The compiler complains that there is a potential memory leak when I replace a pointer to an object with an new pointer to an object that I have initialized dynamically on the stack. Example:
int* foo(int* h){
int* b = new int(5);
b = h; //Memory leak ... | Since this is a general question, my preferred general approach would be to use a smart pointer handled using RAII within your class.
The smart pointer encapsulates the raw pointer, and handles required memory management for you - when your class is destructed, whatever pointer value is held therein at the time will ... |
6,413,252 | 6,413,346 | Fast approach to wrapping data in a struct/class | EDIT: The main intent is to allow manipulating underlying data as part of an encapsulated struct as opposed to direct data manipulation.
Which of the following approaches is recommended when it comes to wrapping some data inside a struct:
Keep a pointer to the data within the struct:
new s(buf), which stores buf in a ... | Placement new will still call the constructor, wiping out anything that's in the buffer already if such a constructor exists (or is created unknowingly in the future) so I don't think that's a safe option. reinterpret_cast is undefined behavior even though it may appear to work for you. Storing a local pointer seems to... |
6,413,361 | 6,413,570 | Searching a log file |
Possible Duplicate:
Searching using Regex in VIM or elsewhere
I'm searching a huge ~600 Mb file for a particular pattern which is 7 Hexadecimal values long. The Problem is
the 'pattern' could be on the next line and
there are several addressing lines.
I got rid of problem 1 by getting rid of all the carriage re... | Python, just read in line, split, chuck the first part, concat the hex into a string, and search. Something like this would work:
hex = ""
for each line in lines:
tmp = line.split() // split on whitespace
hex += tmp[1:] // grab everything after address
if hex.contains(pattern):
# do something
Or use a reg... |
6,413,369 | 6,413,403 | meta-programming: inherit from every class in a boost mpl::vector | I wish to inherit from a set of classes contained in a boost mpl::vector. Is this possible?
Specifically, I wish to extend test for arbitrary many template parameters, passed as a mpl::vector.
template<class T>
struct Slice
{
public:
virtual void foo(T v) const = 0;
};
struct A{};
struct B{};
template <class T1, c... | You want to use mpl::inherit_linearly
|
6,413,466 | 6,413,513 | Templated typedef soup using boost graph library | I am trying to create a class that expands on the behavior of the boost graph library. I would like my class to be a template, where the user supplies a type (class) which will be used to store properties at every vertex. That's just background. I'm struggling with creating a more succinct typedef to use in defining ... | typedef typename boost::graph_traits<GraphType>::vertex_descriptor VertexType;
// ^^^^^^^^
Should fix it, I don't know where you tried to put it though.. you might have other problems I don't see.
|
6,413,642 | 6,413,723 | Window doesn't appear | I have written a small program to create a window. I have made this program before, but now I'm trying to recollect all the things for myself.
When I was done writing the program, the window won't appear, and when I compare my code to the book I'm learning from, its the same. What am I missing/doing wrong?
#include <w... | Compare class names:
wc.lpszClassName = "WindowClass1";
hWnd = CreateWindowEx( NULL, "WindowClass", ...
The best way to find such errors is to check return code of every API.
|
6,413,901 | 8,549,112 | How to implement editor using QTextEdit with toolbar | I'm looking for an example on how to implement a typical rich text editor using QTextEdit.
What I need to implement is a toolbar containing formating functions like:
- bold, underline, intalic
- font family, size
- foreground, background color
- text-alignment
Something like this is implemented in QtCreator in designer... | tada! the answer to your question
all you have to do is google, and study the code. if ever you are having difficulty with anything, please refer to Qt's documentation first before asking.
|
6,414,030 | 6,414,247 | Is the comma in a variable list a sequence point? | In the following type of code is there a sequence point between each variable construction, or is the result undefined?
int a = 0;
int b = a++, c = a++;
I wasn't able to find in the standard a specific reference to a sequence point here. Does that mean it is undefined, or just that I failed in my search? The completio... | I believe behavior is well-defined because of 8[dcl.decl]/3
Each init-declarator in a declaration is analyzed separately as if it was in a declaration by itself.
Which is even additionally explained in a footnote as
A declaration with several declarators is usually equivalent to the corresponding sequence of declara... |
6,414,196 | 6,414,250 | How to add std::swap for my template class? |
Possible Duplicate:
how to provide a swap function for my class?
There are some questions about this, but a lot of contradictions (person A giving solution A' with many upvotes with person B saying it's UB) or "only works if the compiler supports ADL" is answered.
So, say I have the following template (container) cl... | You are not allowed to overload functions in the std-namespace.
Declare swap as a free function, overloaded in the same namespace as your class C:
template<class T>
void swap(C<T>& x, C<T>& y) { x.swap(y); }
The right way to swap is to import std::swap and use a non-qualified version (which is retreieved via namespa... |
6,414,263 | 6,414,320 | Possible forms to send something to standard error | I'm working with the output of a program to which I have the C++ source code. The program sends output to stderr, and I need to know where/how the output is calculated in the source code.
I know that one form to send something to stderr is
std::cerr << "foo";
I use grep to see if this form is used, but I can't find it... | It's not
cerr < "foo"
but
cerr << "foo"
You can try to grep for clog (redirected to the standard error stream) too :
clog <<
You can also search for stderr and perror which are the old C ways to output to standard err
|
6,414,290 | 6,414,513 | Class with map containing function pointers of another class | What I wish to do is have a class that contains a map of function pointers of a second class, but the name of the second class should not matter (cannot be hard coded into the first class) I would really like to be able to implement this WITHOUT using macros. I have followed the examples from learncpp.com on function p... | The name of the class is a part of the type of the function pointer, which becomes part of the map's type, which becomes part of MyClass. Depending on how strong is the requirement "cannot be hard coded", perhaps a template would be sufficient?
#include <string>
#include <map>
template<typename T>
class Class1
{
ty... |
6,414,638 | 6,420,044 | CERN ROOT Extract Data from TNtuple | I am using CERN's ROOT framework (required), and I want to take data from a TNtuple and graph it. I can either graph the data when I create the TNtuple, or after I write it to a .root file. Some of the support documentation suggested that I create a TTree, but that seemed like it might be overkill/roundabout since I ... | As TNtuple inherits from TTree, you can use all the methods presented in the support documentation for TTrees directly on the TNtuple.
This especially means that you can use TTree::Draw() which is typically more than sufficient for quickly graphing the data. This function is documented here.
For more elaborate plots yo... |
6,414,689 | 6,414,989 | 32 bit library on 64 bit system | Can it cause any problem if I use 32 bit library on a 64 bit system?
What could be the incompatibilities?
I know this question is too vague. An example :
I tried to setup FreeGlut 32bit library with VS2010 on windows 7 64bit. There were a lot of issues at first.So, I was looking for 64bit of FreeGLUT, thinking 32bit F... | 64 bit Windows is fully capable of running 32 bit applications. In fact, the default configuration for Visual C++ is to build an x86 application regardless of the operating system it is running on.
There are some gotchas you have to be aware of when running a 32bit app on 64bit Windows. For instance, there's registry r... |
6,414,714 | 6,414,776 | Arbitrary precision arithmetic with GMP | I'm using the GMP library to make a Pi program, that will calculate about 7 trillion digits of Pi. Problem is, I can't figure out how many bits are needed to hold that many decimal places.
| 7 trillion digits can represent any of 10^(7 trillion) distinct numbers.
x bits can represent 2^x distinct numbers.
So you want to solve:
2^x = 10^7000000000000
Take the log-base-2 of both sides:
x = log2(10^7000000000000)
Recall that log(a^b) = b * log(a):
x = 7000000000000 * log2(10)
I get 23253496664212 bits. I ... |
6,414,821 | 6,415,582 | MFC OK/Cancel Dialog Button Override? | Language: C++
Development Environment: Microsoft Visual C++
Libraries Used: MFC
Pretty new to MFC, so bear with me. I have a dialog that is launched via DoModal(). I'm attempting to add buttons to this dialog that will replace the default "OK" and "Cancel" buttons. Right now, I can't quite figure out how to do this. I ... | To wire up your dialog to terminate and return IDSAVEONE, you need to add a click handler to the Save One button and have it call EndDialog:
void CSAPrefsDialog::OnBnClickedSaveone()
{
EndDialog(IDSAVEONE);
}
If you add the click handler through the dialog editor (e.g. by double-clicking on your button) then the n... |
6,414,829 | 6,414,997 | Adding one to matched number in substitution regex | I have a file full of C++ code which is a bunch of small functions that return a number. I am trying to replace each number with the number plus one if the number is greater than 2. So,
int blah() { return 5; }
would become
int blah() { return 6; }
but
int blah() { return 1; }
would remain the same.
How is this done... | A bit ugly, but should work:
s/\{\s*return\s+(\d+)\s*;\s*\}/$1 > 2 ? "{ return " . ($1 + 1) . "; }" : $&/ge;
|
6,414,963 | 6,415,483 | Not able to write to a file | My programs have been running properly for over a year. Today I copied the files onto a different system and compiled every program.
When I compile and run from Dev-c++ it writes data onto a text file like its supposed to, but when I click on the executable it creates, it does not write data onto the file. Everything e... | The best and easiest way is to give the full path of the output file rather than just the filename. That way, you can be sure where the file went, and not have to search for it everywhere. If you are using Windows, the output file might be somewhere in system32. But I could be wrong.
|
6,415,003 | 6,416,365 | Thread Safety Testing | I currently use googles' gtest to write my unit tests, but it doesn't look like it can test thread-safety (that is, accessing something from multiple threads and ensuring it behaves according to spec).
What do you use to test thread safety? I'd like something cross-platform, but, it definitely has to work on Windows a... | If multithreaded code isn't immediately, obviously, provably correct then it is almost certainly wrong. And if it is, you don't need to test it.
Seriously: shared mutable state should be extremely localised and rare, and the classes that do it should be demonstrably correct.
Your threads should normally interact via sa... |
6,415,231 | 6,670,854 | threading a function | I have a recursive function that I want to thread, using either windows threading or boost threading. I have examples for how to do threading both ways, but I am not sure how to implement either, into my function. Below is the example of my boost threading.
struct ThreadDemo {
ThreadDemo( int secs ) : secs_(secs)... | Well, what you have looks like a functor - I think you are confusing that with a thread.
To make a thread in boost (or windows, or pthreads), all you need a function.
Here is a great reference (It is the one I used when first learning Boost threads) http://drdobbs.com/cpp/184401518
|
6,415,257 | 6,415,389 | generating jpeg images from Kinect with openNi/NITE | I am trying to generate pass the image frames to a face-detection/tracking algorithm from the Kinect. I've seen that the best way to generate jpeg images from openGL textures is via libjpeg but I'm clueless on how to start. This is what I have on my code now:
//draw image frame to texture
const XnRGB24Pixel*... | OpenGL does not deal with image files. If you want to store an image to a file, passing it to OpenGL is not doing the right thing to do. Instead of passing the data to glTexImage2D you should pass it to libjpeg or another image file access library.
Have a look at imlib2 http://docs.enlightenment.org/api/imlib2/html/
|
6,415,396 | 6,415,463 | When is posix_memalign/memalign used? |
Possible Duplicate:
When do we need to use posix_memalign instead of malloc ?
When would you need "size bytes of memory such that the allocation's base address is an exact multiple of alignment" over just a simple malloc()?
I believe it is memalign() under Linux and posix_memalign() under Mac OS X/BSD.
| One of the most common use cases is when working with SIMD code (SSE, AltiVec, AVX, Neon, etc) where you typically need all buffers to be aligned on a SIMD vector boundary (16 byte or 32 byte alignment).
Another common alignment requirement is virtual memory page alignment (4 kB typically).
|
6,415,506 | 6,415,686 | openCV in Windows mobile | I want to display camera output from a mobile phone (with Windows mobile OS) using openCV and C# / C++. If you have any useful link / code, please share in this thread.
| Use the native API for doing this if you can, unless there's a specific reason you want to use OpenCV.
Windows Mobile: using phone's camera with C#
There's a couple of useful links on this site.
|
6,415,509 | 6,415,550 | What restrictions does ISO C++03 place on structs defined at function scope? | We're not allowed to define a functor struct inside a function because one is not allowed to use function declared structs in the instantiation of function templates.
Are there any other significant pitfalls to be aware of? E.g. would this be bad:
int foo()
{
struct Scratch
{
int a, b, c;
};
std... | 1. C++ standard forbids using locally-defined classes with templates.
14.3.1/2: A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.
A code example:
template <class T> class X { /* ... */ };
... |
6,415,817 | 6,415,863 | which STL container to use for inter-related data? | First of all, this is a game project.
I need to have objects called Skill, that contain their string name, some other members, and a member that is a set of other Skill objects called "requirements". (This will be a list of prerequisite Skills that the given Skill requires)
In what sort of STL container should I put a ... | You don't define container requirements by what they need to contain, you define it by what operations will be common and how fast they need to operate.
Somewhere there's a wonderful diagram, kind of like a flow chart, that guides you through selecting a container. If I find it I'll update this answer.
Edit: Here it is... |
6,415,906 | 6,415,943 | How does .h, .lib & .dll works together | To use FreeGlut librarie function, I had to do the following,
Added freeglut.h as a Header File
Added freeGlut.lib as a Resources File
Copied freeGlut.dll to my windows/SysWOW64 folder
But, how this whole system(.h, .lib & .dll) is interrelated with each other?
I know, the most basic thing is add a header file with ... | You have to include the header files so that the compiler understands the declarations of various types and functions that are exposed/used by the library.
The library files(lib or dll) contain the object code to which the code using the library links to.
for lib the linkage is static and happens at compile time.Using ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.