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,440,186 | 6,440,241 | copying single character using std::copy | I am trying use std::copy to copy from two different iterator. But during course of execution these two iterators can be pointing to same location. Why in this situation they do not copy the single characters.
std::string str1 = "ABC";
std::string::iterator itr1 = str1.begin();
std::string::iterator itr2 = str1.begin(... | The right bound of the range in STL is not inclusive. If you give it the same iterator twice, the result is an empty range. You want this:
std::copy(itr1,itr2+1,result.begin());
But then, beware that you are writing to a location with no reserved memory, which is Undefined behavior. You must use a back_insert_iterator... |
6,440,280 | 6,440,555 | Valgrind memcheck result analysis of a bison/flex parser | I am running memcheck on my program and i'm trying to solve the memory issues.
Memcheck output :
==29633== 3,443 (128 direct, 3,315 indirect) bytes in 2 blocks are definitely lost in loss record 7 of 8
==29633== at 0x4A07D2E: operator new(unsigned long) (vg_replace_malloc.c:261)
==29633== by 0x42027F: PDcbk(cpf... | Well, you have map of pointers to dynamically allocated objects of class Powerdomain.
The hash map itself did not allocate that memory, so it doesn't clean it up for you.
What you have to do is to free that memory yourself once you don't need it, for example:
for (PowerdomainHashMap::iterator i = powerdomainMap.begin (... |
6,440,391 | 6,440,637 | On a float rounding error | I do not understand the output of the following program:
int main()
{
float x = 14.567729f;
float sqr = x * x;
float diff1 = sqr - x * x;
double diff2 = double(sqr) - double(x) * double(x);
std::cout << diff1 << std::endl;
std::cout << diff2 << std::endl;
return 0;
}
Output:
6.6322... | float diff1 = sqr - x * x;
double diff2 = double(sqr) - double(x) * double(x);
Why diff1 is not equal to 0?
Because you have already cached sqr = x*x and forced its representation to be a float.
To calculate sqr - x * x compiler increases float precision to double. Why?
Because that is how C did things back befor... |
6,440,392 | 6,444,633 | End iterator invalidation rules | Regarding this question on iterator invalidation rules, it seems obvious that the spirit of the standard means, for example, that "an erase in the middle of the deque invalidates all the iterators and references to elements of the deque" also refers to the end iterator.
However, I can't find anywhere that the standard ... | For example, 23.1/10:
no swap() function invalidates any references, pointers, or iterators referring to the elements of the containers being swapped. [ Note: The end() iterator does not refer to any element, so it may be invalidated. —end note ]
I do not know if we can be certain that iterator referring to an elemen... |
6,440,483 | 6,440,556 | How to check null class in C++ | How do I check if a class is null or not in C++? Suppose I have class Line:
Line line[1000];
if (line[0] == NULL)
cout << "NULL";
else
cout << "NOT NULL";
I get this error message:
no match for 'operator=' in 'line[i] = 0'
| The code
Line line[1000];
creates 1000 Line objects and stores them in the line array. The test against NULL makes no sense. You could define
Line* line[1000];
In that case you need to initialize the array and your test would work.
|
6,440,614 | 6,440,702 | Disable warning in MSVC++2010 | I have the following code:
/** Stupidly copies unicode chars into normal chars. */
std::string wstring2string(__in const std::wstring& s)
{
std::string temp(s.length(), ' ');
#pragma warning(push)
#pragma warning(disable: 4244) // possible loss of data
std::copy(s.begin(), s.end(), temp.begin());
#pragma warni... | Well to get rid of this warning you need to add the #pragma warning... around your header file that includes the function. In your case this is xutility. Which is included by multiple other files. So it will be difficult to find. But you can try it this way.
#pragma warning(push)
#pragma warning(disable: 4244) // possi... |
6,440,621 | 6,440,778 | Is this a valid workaround to the constructor issue with mixins? | As I understand there is a problem with mixins where, if you want to use something other than a no-arg constructor, the objects you use your mixin on will either have to have a common constructor signature or you have to use initializer methods in the classes you want to use the mixin with.
This seems to be kind of a w... |
You're leaking memory if an exception is thrown during construction,
The base class must have a default constructor to be be constructed first and then assigned.
Better do:
Decorator(const T& initializer) : T(initializer)
{
}
and use:
Decorator<Base> d1((Base()));
Decorator<Base> d2(Base("decorated"));
Decorator<Der... |
6,440,699 | 6,440,880 | c++0x library availability in any compiler? | The standard will doubtless take years to put in place, which stinks because it looks great. But I was reading it, and at least the library additions (hash maps in particular) would be really useful right away. I noticed in the g++ docs that I can get 4.3 or better and use a flag to request the new features, whatever... | GCC with option -std=c++0x already covers a pretty good subset of C++0x. Version 4.4 is already pretty usable, 4.6 even moreso. It's missing template aliases, but many extremely useful language features as well as a very large part of the library is there and fully functional.
Here is the full feature list.
|
6,440,730 | 6,440,785 | is there anyway to rebuild some saved classes from their vtable? | I'm copying some objects into a file and they all are derieved from same class. but I want to be able to call their functions after loading them to do what that class should do, here's what i did until now:
#include <iostream>
#include <fstream>
using namespace std;
struct a
{
virtual void print()
{
c... | Please, don't do that. Never.
Basically, what you do is using a old-style cast to cast a a* to a char*. This results silently in a reinterpret_cast between two unrelated types, and is highly implementation dependant. You cannot rely on the underlying memory layout: it might change for any reason (even when using the sa... |
6,440,812 | 6,440,983 | C++ What does the size of char16_t depend on? | This is also related to char32_t and any intXX_t. The specification points out that:
2.14.3.2:
The value of a char16_t literal
containing a single c-char is equal to
its ISO 10646 code point value,
provided that the code point is
representable with a single 16-bit
code unit.
5.3.3.1:
[..] in particular [.... | 3.9.1 Fundamental types [basic.fundamental]
Types char16_t and char32_t denote distinct types with the same size, signedness, and alignment as uint_least16_t and uint_least32_t, respectively, in , called the underlying types.
This means char16_t is at least 16 bits (but may be larger)
But I also believe:
The va... |
6,440,993 | 6,441,039 | C++ Printing value of pointer gives strange result | When I compile and run this C++ code, I am not getting the output I expected.
#include <iostream>
using namespace std;
int main()
{
int * i = new int;
long * l = new long;
char * c = new char[100];
float * f = new float[100];
cout << "i " << i << endl;
cout << "l " << l << endl;
cout << "c... | operator << for std::ostream and std::wostream is defined in special way for char pointers(char*, const char*, wchar_t* and const wchar_t* to print out a null-terminated string. This enables you to write
const char* str = "Hello, World";
std::cout << str;
and see a nice string on your stdout.
To get the pointer valu... |
6,441,098 | 6,441,159 | a question about vector in c++ | I read some code written in c++ as following:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int iarr[] = {30, 12, 55, 31, 98, 11, 41, 80, 66, 21};
vector<int> ivector(iarr, iarr + 10);
}
in the above code, I pass iarr and iarr+10 to ivector(iarr, iarr + 10) to ... | Yes, it is allowed and yes, you are doing it right.
You are calling this templated constructor:
template<class InputIterator>
vector(
InputIterator _First,
InputIterator _Last
);
The template parameter InputIterator is int* (this is the type of the expressions iarr and iarr + 10).
Since the documenta... |
6,441,743 | 6,460,624 | How to retrieve codepage from cURL HTTP response? | I'm using lib-cURL as a HTTP client to retrieve various pages (can be any URL for that matter).
Usually the data comes as a UTF-8 string and then I just call "MultiByteToWideChar" and it works well.
However, some web-pages still use code-page encoding and I see gibberish if i try to convert those pages to UTF-8.
Is... | I used DetectInputCodepage in IMultiLanguage2 interface and it worked great !
|
6,441,925 | 6,441,953 | std::map, polymorphism and delete | I have a problem using a C++ map to store pointers to a base class and some derived class.
Let me explain by a rather long but simple code:
#include <map>
#include <iostream>
struct foo{ int dummy[4]; };
struct bar{ int additionnal[4]; };
class Base
{
private:
struct foo *_internal_structure;
public:
Base() {... | Where is your virtual destructor???!!!
Read this, and never forget. Really, you have just broken one of the 10 C++ commandments... :))
|
6,442,063 | 6,442,265 | Calculate frequency of triples in a C array for indexing | I have an array of integers (possibly thousands), like
int p[] = {0, 0, 0, 1, 0, 1, 2, 0, 2, 1, 0, 1, 0, 0, 0, 3, 0, 3, 5, 1, 7, ...
from which I want to generate a set of indices for each unique triple; for the list above, something like:
0, 1, 2, 1, 0, 3, 4, ...
I've coded up a simple C++ implementation (though a p... | Agreed with Armen that it's generally OK. I would probably make a map with triples as keys and a set of indices as values:
typedef std::set<size_t> index_set;
typedef std::tuple<int,int,int> triple;
typedef std::map<triple, index_set> frequency_map;
And then:
const auto t = std::make_tuple(p[i], p[i+1], p[i+2]);
freqs... |
6,442,129 | 6,442,972 | Accessing a class template parameter type inside a member function with a lambda fails | I have a class template with a member function that has a lambda which wants to use a class template parameter type. It fails to compile inside the lambda but succeeds, as anticipated, outside the lambda.
struct wcout_reporter
{
static void report(const std::wstring& output)
{
std::wcout << output << st... | Use typedef:
template <typename reporter = wcout_reporter>
class agency
{
typedef reporter _myreporter;
public:
void report_all()
{
reporter::report(L"dummy"); // Compiles.
std::for_each(reports_.begin(), reports_.end(), [this](const std::wstring& r)
{... |
6,442,193 | 6,444,838 | QLineEdit thousand separator | With a QLineEdit is it possible to display the thousand separator of a number while user enter it
Which is the best way to do that ?
| You can connect a slot to the void QLineEdit::textEdited ( const QString & text ) signal of your QLineEdit and add some space/separator in the edited string via the setText() method. It should work since textEdit won't be emit-ed again.
The Qt doc says :
Unlike textChanged(), this signal (textEdited) is
not emitted ... |
6,442,314 | 6,444,252 | Visual C++ (2008) debugging snapshot | Sometimes I need to keep track of several lines of code where variable values change on the object I am interested in. When the object changes, I need to compare the variables to see what is happening, and whether it is different than expected values. This is similar to a watch window, but one that can be saved and sho... | Make a screenshot of your desktop when variables change. You'll have the code (you can select the exact code to further enhance), and the variables as a visual snapshot. The variables that just changed will also as you know be indicated with red color.
You can also resize the window smaller if you can fit all info you ... |
6,442,328 | 6,442,372 | What is the difference between #define and const? |
Possible Duplicates:
Why would someone use #define to define constants?
difference between a macro and a const in c++
C++ - enum vs. const vs. #define
What is the difference between using #define and const for creating a constant? Does any have a performance advantage over the other? Naturally I prefer using the con... | The #define directive is a preprocessor directive; the preprocessor replaces those macros by their body before the compiler even sees it. Think of it as an automatic search and replace of your source code.
A const variable declaration declares an actual variable in the language, which you can use... well, like a real v... |
6,442,576 | 6,442,630 | C++: Identifying the type of the object | I'm curious what constructs or language features, available in both the current C++ as well as in C++11, can be used to deduce the type of an object. An example:
class Base {
};
class DerivA
: public Base {
};
class DerivB
: public Base {
};
void foo(Base* obj) {
// Identify if `obj` is a `DerivA` or a `... | You can use dynamic_cast for that:
if(DerivA * derivA = dynamic_cast<DerivA*>(obj)){
// it is a DerivA
}
|
6,442,591 | 6,442,841 | Library to manipulate terminal space? | I want to make a rogue-like game for my assignment. I need something to let me handle the x and y pixels on the terminal screen as well as key events, so I can control my character. Also, will it be able to repaint a region of a terminal only? i.e. I don't want to repaint the terminal every time I move my character bec... | If your target is a command line application in a linux environment programmed with C++, I would suggest that you take a look at the ncurses library.
|
6,442,709 | 6,445,691 | boost fusion question | I'm having trouble compiling the following (I'm new at fusion). In particular, I'm not sure where "_" (in is_same) comes from? From boost::lambda? Boost::mpl? What include do I need for this to compile?
template <typename T>
struct check
{
const T& value;
check(const T& v) : value(v) {}
template <typename X>
... | Yes, that indeed is meant to be boost::mpl::_, as demonstrated in the fusion::filter_if documentation, so you should only need #include <boost/mpl/placeholders.hpp> and a qualification or using declaration to bring _ into scope.
|
6,442,722 | 6,447,532 | Why does concepts make C++ compile slower? | What kind of evil magic is it trying to do!?!
I was listening to a Q&A session with herb sutter and one question was about concepts. Herb mention it made compilers slower (while the source remains unchanged) and the section was significantly larger then the section on templates.
Why does it do this? where can i find do... | Note: the following answer (and the question it answers) pertains to the old C++0x version of concepts and has little relation to the version of the feature added to C++20.
First of all, Herb didn't say that concepts themselves made compiling slower. He said that conceptizing the C++ standard library made any code usi... |
6,442,730 | 6,442,781 | Running Threads Simultanously using Qt | I have a problem. I have a Qiwidget which has 2 pushbuttons. On pressing one button i need to play back 1 file using some playback technique. On clicking the other button I want to playback another file. I made the classes using the playback's for the 2 files as threads. But when i try to push the 1st button my applica... | You should call
playSource1->start();
not run(). See the "Starting a Thread" section in the Qt Starting Threads with QThread documentation.
|
6,442,812 | 6,443,090 | Does boost::asio::io_service preserve the order of handlers? | Does boost::asio::io_service guarantee that handlers are called in the same order that they are given via post()? I can't find anything saying this in the documentation. Assume that calls to io_service::post are serialized.
| The current implementation does execute things in the sequence you post them, but ordering is only guaranteed for handlers that are explicitly post()ed through a strand.
|
6,442,835 | 6,442,887 | How does the compiler interpret this expression? | While reading through a C++ book, I came across an expression which was not explained properly (or maybe I just didn't understand the explanation). This is the expression:
c = a+++b;
Which of these does it mean?
c = a + (++b); // 1
c = (a++) + b; // 2
Thanks.
| Its interpreted as:
c = a++ + b; //which is same as you're ve written : (a++) + b
Its following the Maximal munch rule.
|
6,442,859 | 6,442,921 | Problem about usage of "this" keyword in C++ | class Monitor
{
private:
int rate;
Monitor(int rate)
{
this.rate = rate;
}
}
This is my code. I try to set the private member "rate" with local member that passes through constructor "rate". But I could use it like that In C#.
The error is:
expression must have class type
| this is a pointer, as others have said, but it's much better and more correct to use the base initializer list:
class Monitor
{
int rate;
public:
Monitor(int rate) : rate(rate) { }
};
That way, Monitor::rate gets initialized to the right value, rather than first default-initalized and then assigned. For more gen... |
6,443,027 | 6,443,187 | How to write R extension using a static library | Hi I am trying to build an R package using a pre-compiled static library and a single header file. What is the best way to do so?
Because I didn't find any information on it (only on creating R packages that compile from src), I settled on writing a thin C++ wrapper class in the extension src directory. I also added th... | First off, any extension package to R containing compiled source code will be dyanmically linked -- as R loads it at run-time.
That said, any external dependencies of your code could be statically linked into the extension package. For that to happen, you could try to just list the static library with its full path in ... |
6,443,105 | 8,287,861 | Is it possible to stream video in ITU-R BT.656 format? | I have to make an application that stream a playlist in the ITU-R BT.656 video format. Frankly speaking it's my first time hearing about this format. It seems to be used for DV streaming. I have been googling around for hours and so far the only BT656 encoders i found are hardware one. Is it possible to do it programma... | A BT.656 data stream is a sequence of 8-bit or 10-bit words, transmitted at a rate of 27 Mbyte/s.
Essentially this is a digitized raw video. While conceptually, streaming this might not be impossible, you cannot really afford to stream at 27 MBps. If indeed that is what you need to do, converting each frame into a BMP... |
6,443,223 | 6,456,371 | Can Klocwork (or other tools) be aware of types, typedefs and #define directives? | I have been looking for tools to help detect errors that prevent a program from running properly as 64-bit code. Most recently, I've been toying with Klocwork and its custom checkers feature, which lets me navigate the source code as a tree using XPath. This is useful as a "smarter" alternative to regular expressions, ... | Not entirely sure if this is what you want, but you can always resolve types quite easily with built-in functions. For example, answering your question (although perhaps not your underlying need):
//ForStmt / Init::ExprStmt / Expr::BinaryExpr [ $type := Left.getTypeName() ] [ $type = 'int' | $type.contains('long') ]
T... |
6,443,230 | 6,443,267 | When auto is used against array, why it's converted to pointer and not reference? | See the below example:
int arr[10];
int *p = arr; // 1st valid choice
int (&r)[10] = arr; // 2nd valid choice
Now when we use auto against arr then, it chooses the 1st choice.
auto x = arr; // x is equivalent to *p
Is there a reason for choosing a pointer and not reference for array ?
| Yes. In that expression, the array decays into pointer type, due to lvalue-to-rvalue conversion.
If you want array type , not pointer type, then do this:
auto & x = arr; //now it doesn't decay into pointer type!
& in the target type prevents the array from decaying into pointer type!
x is an array and not a pointer, ... |
6,443,234 | 6,443,334 | Why using "SND_SYNC" in a "QueueUserWorkItem" bad? | Larry Osterman writes about a real error found in Microsoft's code, the offending code is
static DWORD WINAPI _PlayBeep(__in void* pv)
{
UNREFERENCED_PARAMETER(pv);
PlaySound(L".Default"NULL, SND_SYNC | SND_ALIAS);
return 0;
}
LRESULT WndProc(...)
{
:
:
case WM_KEYDOWN:
if (!_AcceptInpu... | Read the answer page, it's got a very detailed explanation
http://blogs.msdn.com/b/larryosterman/archive/2009/06/29/what-s-wrong-with-this-code-part-26-the-answer.aspx
Basically, don't use QueueUserWorkItem for long-running work items because this can cause thread exhaustion in your process, or even deadlock in a very ... |
6,444,071 | 6,444,110 | Circular references in C++ in different files | If i want a circular reference but in two different files in C++, how would I implement that?
For example
AUnit.h
#inclue <BUnit.h>
class AClass : public TObject
{
__published
BClass * B;
};
BUnit.h
#include <AUnit.h>
class BClass : public TObject
{
__published
AClass *A;
};
I can't make ... | I assume you're talking about circular dependencies.
The answer is indeed to use a forward declaration, such as:
AUnit.h
#include <BUnit.h>
class AClass : public TObject
{
BClass *B;
};
BUnit.h
class AClass; // Forward declaration
class BClass : public TObject
{
AClass *A;
};
You could even have a forward dec... |
6,444,364 | 6,444,391 | convert a line to a Node in C++ | I'm trying to write a function that takes a line as a string and converts it into a Node.
Node convertLineToNode(string line){
char lineC[] = line;
Node *n = new Node();
n->lastname=strtok(lineC," ");
n->name=strtok(lineC," ");
n->ID=strtok(lineC," ");
}
However it doesn't work properly. It expect... | The C++ way would be this:
Node* convertLineToNode(std::string const & line)
{
std::istringstream iss(line);
Node *n = new Node();
iss >> n->lastname
>> n->name
>> n->ID;
return n;
}
consider returning a shared_pointer instead of a raw one
|
6,444,505 | 6,444,743 | Can anyone tell me what does this mean | This is a very basic doubt, but clarify me please
#define TLVTAG_APPLICATIONMESSAGE_V "\xDF01"
printf("%s\n", TLVTAG_APPLICATIONMESSAGE_V);
means what will be printed.
| To go step by step (using the C++ standard, 2.13.2 and 2.13.4 as references):
The #define means that you substitute the second thing wherever the first appears, so the printf is processed as printf("%s\n", "\xDF01");.
The "\xDF01" is a string of one character (plus the zero-byte terminator), and the \x means to take th... |
6,444,566 | 6,444,599 | An unhandled exception of type 'System.Reflection.TargetParameterCountException' | I created a BeginInvoke so I could write to a text box from a non-UI thread. Thread A calls a delegate which runs testFunc in thread A's context. testFunc then does a BeginInvoke which runs the empty function ControlBoxDelegateMethod. If the BeginInvoke line is removed, the program runs. But if it is left in, I get... | ControlBoxDelegateMethod takes two parameters (a Label^ and an int), but you're only passing one (an int named which). You're missing the first parameter.
So, it should probably go like this:
local_long_textBox->BeginInvoke(gcnew ControlBoxDelegate(this,&Form1::ControlBoxDelegateMethod), your_label, which);
|
6,444,581 | 6,444,849 | Will buffer size make a difference in time cost while reading files? | I have two options concerning buffer sizes when reading files.
char* buffer = new char[aBlock];
myFile.read(buffer,aBlock);
and,
char* buffer = new char;
while (!myFIle.eof())
myFile.read(buffer,1);
Will there be a considerable time cost difference?
Be aware that as buffer I'm referring to that char* buffer in th... | You will already be reading buffered, as it does not read directly from the file to the buffer you put into the call to read, but will first go to the buffer inside the fstream (a filebuf).
The first sequence will still be quicker because it will loop fewer times, but not as drastic as people may think because the file... |
6,444,831 | 6,444,874 | Thread-safe string buffer variables in C++ DLL | I am writing a Win32 DLL in MSVC++2010 with exported functions. Some of those functions return filenames as LPCSTR. Because I sometimes need to fiddle with strings before, I am currently using a global buffer variable of length 32184 which should cover any filename that can occur in Windows which I then always initiali... |
Windows API functions are generally thread-safe, with certain limitations (eg, you cannot FindNextFile on the same handle from two threads at the same time, but you can with two different handles). For boost functions, consult the documentation, but generally speaking filesystem/regex functions should be safe as long ... |
6,444,842 | 6,444,999 | Efficient way to check if std::string has only spaces | I was just talking with a friend about what would be the most efficient way to check if a std::string has only spaces. He needs to do this on an embedded project he is working on and apparently this kind of optimization matters to him.
I've came up with the following code, it uses strtok().
bool has_only_spaces(std::st... | if(str.find_first_not_of(' ') != std::string::npos)
{
// There's a non-space.
}
|
6,444,876 | 6,444,894 | C++ reading buffer size | Suppose that this file is 2 and 1/2 blocks long, with block size of 1024.
aBlock = 1024;
char* buffer = new char[aBlock];
while (!myFile.eof()) {
myFile.read(buffer,aBlock);
//do more stuff
}
The third time it reads, it is going to write half of the buffer, leaving the other half with invalid data. Is there a... | istream::gcount returns the number of bytes read by the previous read.
|
6,444,918 | 6,447,131 | Relatively Prime Numbers | How to make a function in c++ to determine if two entered numbers are relatively prime (no common factors)?
For example "1, 3" would be valid, but "2, 4" wouldn't.
| Galvanised into action by Jim Clay's incautious comment, here is Euclid's algorithm in six lines of code:
bool RelativelyPrime (int a, int b) { // Assumes a, b > 0
for ( ; ; ) {
if (!(a %= b)) return b == 1 ;
if (!(b %= a)) return a == 1 ;
}
}
Updated to add: I have been out-obfuscated by this answer from ... |
6,445,177 | 6,445,364 | Why allocate memory? (C++) | I am trying to understand memory allocation in C++.
A question that comes to my mind is why is it so necessary to allocate memory? And what happens if we use memory without allocating it?
Also, I was shocked to see how careless C++ is on memory allocation. If gives free access to memory through arrays with no bounds ch... | Why is it neccessary to allocate memory?
Because that way, you mark the memory as yours. Nobody else can use it. It also verifies that there is in fact memory available. If your system only has 1000 bytes of memory, just picking byte 1500 to store some data at is a bad idea.
What happens if we use memory without all... |
6,445,276 | 6,445,341 | returning local variables | I came across an issue today regarding local variables. I learned that...
int * somefunc()
{
int x = 5;
return &x;
}
int * y = somefunc();
//do something
is bad, unsafe, etc. I'd imagine that the case is the same for...
int * somefunc()
{
int * x = new int;
x = 5;
return x;
}
int * y = s... | As it stands, the second example is wrong. You probably meant this:
int * somefunc()
{
int * x = new int;
*x = 5; // note the dereferencing of x here
return x;
}
Now this is technically fine, but it is prone to errors. First, if after the allocation of x an exception happens, you have to catch it, delete x... |
6,445,841 | 6,445,880 | C++ static_cast runtime overhead | See the code below.
a) Does, in this case (simple inheritance, no virtual members), the static cast in B::df() have any overhead (whatsoever)? I found some conflicting answers to similar questions, that's why I am asking...
b) I was thinking about making const M1 * func private in A and introducing a new private field ... | static_cast<T>(e) is equivalent to creating an invented temporary variable v in the following way:
T v(e); //where T is an arbitrary type and e is an arbitrary expression.
The runtime cost of a static_cast is exactly the cost of the above statement
|
6,445,927 | 6,446,025 | What is the use of private static member functions? | I was looking at the request parser from the boost::asio example and I was wondering why the private member functions like is_char() are static? :
class request_parser
{
...
private:
static bool is_char(int c);
...
};
It is used in the function consume which is not a static function:
boost::tribool request_p... | This function could easily have been made freestanding, since it doesn't require an object of the class to operate within. Making a function a static member of a class rather than a free function gives two advantages:
It gives the function access to private and protected members of any object of the class, if the obje... |
6,446,140 | 6,446,188 | How to call a method in one object from another object in the same structure | I have the following situation:
class B
{
public:
void methodInB();
};
class C
{
public:
void methodInC();
};
class A
{
public:
void methodInA();
private:
B objB;
C objC;
};
void A::methodInA()
{
objB.methodInB();
}
int main()
{
A objA;
objA.metho... | I think the cleanest way would be to "inject the dependency", that is, to pass objC to methodInB, which would then invoke methodInC on that object:
void A::methodInA()
{
objB.methodInB(objC);
}
// ...
void B::methodInB(C &objC)
{
objC.methodInC();
}
|
6,446,589 | 6,446,608 | size of ArrayList is not known help | I have this code
main.cpp
#include <iostream>
#include "functs.h"
using namespace std;
int main()
{
ArrayList *al = new ArrayList;
return 0;
}
functs.h
using namespace std;
#ifndef FUNCTS_H_INCLUDED
#define FUNCTS_H_INCLUDED
class ArrayList;
#endif // FUNCTS_H_INCLUDED
functs.cpp
#include <iostream>
#inclu... | Design/usage problems in your code notwithstanding, the most obvious problem is that you want to put the class definition in the functs.h file instead of the functs.cpp file:
functs.h:
// This is declaration is highly not recommended for use in header files.
// using namespace std;
#ifndef FUNCTS_H_INCLUDED
#define FU... |
6,446,627 | 6,446,968 | debugging openCV in visual studio 2005 | I am new to Visual Studio 2005 and am trying to get to grips with it. I am using it to compile and debug an application called AAM-library (which I didn't write) which uses OpenCV 1.0. I have compiled the software and now I'm getting a runtime error.
To figure out the reason for the error (I know the line number and f... | Place a breakpoint a few lines before the error or use run to cursor. There is no magical "10 lines before this breakpoint" feature. (Intellitrace can do this for managed code but that's a whole different ballgame)
Also note that concurrent debugging was made a LOT better in VC2008, you might want to consider using a m... |
6,447,106 | 6,447,323 | why Vector doesn't provide the remove() member function while list provides? | If I want to delete all the elements with a value from vector,I call remove algorithm and then call vector's erase member function to physically delete it.
But in the case of list , simple call remove member function and it will delete all elements with that value.
I am not sure why vector does't provide the... | The question is not why std::vector does not offer the operation, but rather why does std::list offer it. The design of the STL is focused on the separation of the containers and the algorithms by means of iterators, and in all cases where an algorithm can be implemented efficiently in terms of iterators, that is the o... |
6,447,208 | 6,447,259 | Do function calls within a function's argument list deepen the stack? | When calling F(argument_expression), is argument_expression evaluated before pushing the stack for F?
For example, when calling F(G(H(arg))), does the compiler first push the stack for H, evaluate H, pop, then push the stack for G, etc? Or does it first push the stack for F, then for G, then for H, then pop back up 3 ... | The parameters are fully evaluated before the called function can run, per spec.
I.e.: In your example, H(arg) will be fully evaluated before G(result of H(arg)) can run, etc.
At any given time you'll have one-level depth of the stack.
|
6,447,261 | 6,460,271 | Write BITMAPINFOHEADER image data to IDirect3DTexture9 | I'm writing a DX9 renderer and currently working on the ability to play AVI movie files. I've been able to retrieve any specified frame using AVIStreamGetFrame(), which returns a packed DIB, and from there I want to be able to copy that bitmap data to an already existing IDirect3DTexture9 *.
My issue is a lack of under... | Got it to work!
Couple notes to consider. My AVI file (a single frame/bitmap in this case) was in a 16 bit format, therefore I had to create my destination texture with D3DFMT_X1R5G5B5. Also, bitmaps are stored upside down, so I had to reverse my pointer and read each row backwards.
Here's the code:
// Retrieve a fra... |
6,447,528 | 6,447,624 | why does ::CreateProcess(path,cmd,...) fail with error "File not found"? | I am trying to have a C++ program call an already made C# program to run in the background.
STARTUPINFO info = {sizeof(info)};
PROCESS_INFORMATION processinfo;
DWORD error1 = GetLastError();
bool x = ::CreateProcess((LPCWSTR)"C:\Convert_Shrink.exe", GetCommandLine(), NULL, NULL, false, 0,NULL,NULL, &info, &processinfo)... | You can:
Use CreateProcessA to match your ANSI file path:
bool x = ::CreateProcessA("C:\\Convert_Shrink.exe", GetCommandLineA(), NULL, NULL, false, 0,NULL,NULL, &info, &processinfo);
* Provide a file path which matches the string format required by your Unicode settings:
bool x = ::CreateProcess(_T("C:\\Convert... |
6,447,688 | 6,447,837 | How to delete parts from a binary file in C++ | I would like to delete parts from a binary file, using C++. The binary file is about about 5-10 MB.
What I would like to do:
Search for a ANSI string "something"
Once I found this string, I would like to delete the following n bytes, for example the following 1 MB of data. I would like to delete those character, not ... | There are a number of fast string search routines that perform much better than testing each and every character. For example, when trying to find "something", only every 9th character needs to be tested.
Here's an example I wrote for an earlier question: code review: finding </body> tag reverse search on a non-null t... |
6,447,714 | 6,454,895 | Calling luabind derived member as a coroutine | The luabind documentation says to call a Lua-derived virtual member from C++, you create a wrapper class derived from luabind::wrap_base and call the function like so:
class BaseWrapper : public Base, public luabind::wrap_base
{
public:
virtual void foo()
{
call<void>("foo");
}
}... | So I've figured out the answer to this problem. It seems that the simplest solution is to pass self from Lua when you construct the object and then look up the function from its table:
On the C++ side:
BaseWrapper::BaseWrapper(luabind::object self) : _self(self)
{ }
virtual void BaseWrapper::foo()
{
luabind::object ... |
6,447,819 | 6,447,881 | How to look for an ANSI string in a binary file? | I would like to find the first occurence of an ANSI string in a binary file, using C++.
I know the string class has a handy find function, but I don't know how can I use it if the file is big, say 5-10 MB.
Do I need to copy the whole file into a string in memory first? If yes, how can I be sure that none of the binary... |
Do I need to copy the whole file into a string in memory first?
No.
Or is there a more efficient way to do it, without the need for copying it into a string?
Of course; open the file with an std::ifstream (be sure to open in binary mode rather than text mode), create a pair of multi_pass iterators (from Boost.Spiri... |
6,447,947 | 6,447,970 | Is stdout Ever Anything Other Than a Console Window? | From http://www.cplusplus.com/reference/iostream/cout/:
By default, most systems have their standard output set to the console, where text messages are shown, although this can generally be redirected.
I've never heard of a system where stdout is anything other than a console window, by default or otherwise. I can s... | On most systems you can redirect the standard input/output/error to other file descriptors or locations.
For example (on Unix):
./appname > output
Redirects the stdout from appname to a file named output.
./appname 2> errors > output
Redirects stdout to a file named output, and all errors from stderr to a file named ... |
6,448,286 | 6,455,476 | Convert IplImage to Qpixmap | How do we convert IplImage to a QPixmap or QImage?
If the only answer is save the Iplimage then load it to the QPixmap, then how do we do that?
| IplImage * ImageToIplImage(QPixmap * qPix){
int width = (qPix->toImage()).width();
int height =(qPix->toImage()).height();
// Creates a iplImage with 3 channels
IplImage *img = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 3);
for(int y=0;y<height;y++)
{
for(int x=0;x<width;x++ ... |
6,448,608 | 6,449,127 | Clustering algorithm with upper bound requirement for each cluster size | I need to do a partition of approximately 50000 points into distinct clusters. There is one requirement: the size of every cluster cannot exceed K. Is there any clustering algorithm that can do this job?
Please note that upper bound, K, of every cluster is the same, say 100.
| One way is to use hierarchical K-means, but you keep splitting each cluster which is larger than K, until all of them are smaller.
Another (in some sense opposite approach) would be to use hierarchical agglomerative clustering, i.e. a bottom up approach and again make sure you don't merge cluster if they'll form a new ... |
6,448,638 | 6,448,729 | Insert into a desired element of an array and push all other elements one spot over in c++ | Having some issues with one small function I'm working on for a homework assignment.
I have a static array size of 20 (shelfSize), however, I only need to use a max of 10 elements. So I don't have to worry about out of bounds etc (the entire array of 20 is initialized to 0).
What I am looking to do is insert an integer... | You should start from the end of the array, this should word for you:
void insert_at(int booknum, int element)
{
for (int i = shelfsize-1;i>element;i--)
bookshelf[i] = bookshelf[i-1];
bookshelf[element] = booknum;
}
Also I recommend that you get used to handling illegal values, for example, what if a u... |
6,448,668 | 6,448,691 | About thread-safety using QThreadStorage | This is a threading question where I basically started making a library thread-safe. My use-case is as follows -
struct <>
{
int thread_specific_value;
}
1) Spin 5 threads for example.
2) Each thread does operation and store thread_specific_value in the above data structure for example. This is dynamically ... | Data stored in QThreadStorage is accessible only from the thread that put it there. Period. If you want to access the same data from other threads, you must store it additionally elsewhere. In particular, the thread-specific value is destroyed on thread exit; if you want to keep the value, save it somewhere before the ... |
6,448,702 | 6,448,808 | MFC Toolbar on Dialog? | I have tried everything I can think of to get a toolbar to show up on my dialog... including trying to create it myself with CreateWindow.. but it won't show up
I created a dialog in the resource editor, and then made a class for it(tried deriving from both CDialog and CDialogEx). Isn't it possible to add a CToolbar co... | Well, there are four steps.
1, CToolBar m_ToolBar; // Meanwhile you create a resource (e.g. IDR_TOOLBAR1)
2, Call CToolBar's Create function
m_ToolBar.Create(this);
3, Call the LoadToolBar function
m_ToolBar.LoadToolBar(IDR_TOOLBAR1);
4, The most important step, call RepositionBars
RepositionBars(AFX_IDW_CONTROLBAR_F... |
6,448,715 | 6,448,727 | STL Container, Speed of Creation/Destruction | Background:
I am creating an efficient(hopefully) collision detection system for my game engine- it's introduced a slight problem when I place large amounts of objects on the screen. My problem is this:
I will be adding and removing objects regularly and I have several manager classes that keep track of the objects at ... | std::set is unlikely to offer better performance: it is a node-based container, so each element requires a dynamic allocation, which can prove expensive.
Consider sticking with std::vector: it offers constant-time random access to all elements in the sequence and constant-time insertion and removal at the end of the s... |
6,448,717 | 6,448,743 | C++ (int) static cast weird error | I have a very weird error with c++.
I have two values, max and singleStep. The number of steps is stepsInt and/or stepsDbl:
max = 100;
singleStep = 0.1;
// This means that I have 100/0.1 = 1000 numbers betwwen 0 and 100
double stepsDbl = max/singleStep;
int stepsInt = (int)(stepsDbl);
cout << stepsDbl << stepsInt;
You... | Try this instead:
int stepsInt = (int)floor(stepsDbl+.5);
The "problem" you're seeing is because of the way floating point numbers are stored internally.
|
6,448,830 | 6,448,839 | C++ Error: Class has-a-relationship with Struct in Same Header File | I'm defining a C++ header file, and for some reason the class I'm creating gives an error when I try to refer to a struct which is defined in the very same file, along with an enumeration class I created.
I'm pretty to new to C++, though I have some experience with Java and C#. Even then, my programming experience is ... | C++ is parsed from the top of the file to the bottom; you need to move your Stats class definition to above your Character class definition.
|
6,448,873 | 6,449,108 | how to make C++ program reads the algorithm from external file? | I know it's a weird question but I want to design a program that will run scenario, this scenario has some functions like searching, deleting ....
these function how they are defined will be up to user, he can define these functionality like defining how the scenario should run.
I'm thinking it can be done in C# by mak... | Since you're using Qt, you might check out their QtScript framework; it might do what you want, and it's already integrated into Qt so you wouldn't have to set very much up to use it.
|
6,448,967 | 6,449,007 | Can i copy 'vector' elements in 'set' using the copy algorithm? | I am getting the run time error in following code. Please let me know can i copy vector elements in set?
#include <iostream>
#include <vector>
#include <set>
using namespace std;
int main()
{
vector<int> v;
set<int> kk;
set<int>::iterator itr;
for (int i = 0; i < 6; i++)
{
v.push_back(i * 2)... | You are not initialising itr:
set<int>::iterator itr = kk.begin();
Or remove itr entirely:
copy(v.begin(), v.end(), inserter(kk, kk.begin()));
In this instance, you could simply initialise kk thus (but if you want to add to kk follow the line above):
set<int> kk(v.begin(), v.end());
|
6,449,002 | 6,449,045 | Qt QHBoxLayout issue? | I use an extended QGroupBox as the widget for QDockWidget in my QMainWindow.
Here is the code snippet:
RzPlaneViewerControlPanelWidget::RzPlaneViewerControlPanelWidget(QWidget *parent) : QGroupBox(parent) {
// TODO Auto-generated constructor stub
init();
}
void RzPlaneViewerControlPanelWidget::ini... | From a quick read, I'd try doing:
hbox->addWidget(scrollbar, 1);
The second (optional) argument to addWidget is the stretch factor. From the Qt docs:
If the stretch factor is 0 and nothing else in the QBoxLayout has a stretch factor greater than zero, the space is distributed according to the QWidget:sizePolicy() of ... |
6,449,014 | 6,449,399 | How to programmatically Paste CSV text into Excel and not just go into one cell? (C++) | I have a list/grid in an MFC (c++) application. I would like the user to be able to copy and paste the data into a spreadsheet.
I've placed the data in the clipboard and the text makes it to the clipboard ok and I can paste it to notepad or Word or Excel, but Excel does not interpret the comma separated value-ness of ... | I used this question and tabs seem to work - but csv still does not
How to paste CSV data to Windows Clipboard with C#
|
6,449,103 | 6,449,302 | Strict aliasing and __m128i type | When using SSE2 intrinsic functions to do bit-wise operations, one has to cast pointers from int* to __m128i*. Does this code break strict aliasing rule?
void bit_twiddling_func(int size, int const* input, int* output) {
const __m128* x = (const __m128*)input;
const __m128* y = (const __m128*)output;
for (... | Yes; it breaks strict aliasing rules. Two different types can't point to the same location in memory. Here you have x pointing to input and y pointing to output, but they're of differing types.
You could change the signature of your function to take __m128* parameters, but it's probably easiest to leave it be. It'll... |
6,449,144 | 6,449,335 | Is this a situation where I'd want to use "using"? | I'm not familiar with C++0x. I just started learning C++ myself about 6 months ago, I have a fairly strong grasp though (for a beginner).
I have a templated class:
template <typename T>
class Node
{
...
}
Then later, I have this:
template <typename T>
class BinaryTree
{
protected:
typedef Node<T>* node_t... | The answer to your question is no, it isn't applicable. using in the context you mean is intended for renaming a templated type while retaining its templated nature. You have a specific instance of the template in mind, so it is not appropriate.
However, part of your concern seems to simply be the overabundance of Bi... |
6,449,198 | 6,449,509 | Using buffers to read from unknown size file | I'm trying to read blocks from a file and I have a problem.
char* inputBuffer = new char[blockSize]
while (inputFile.read(inputBuffer, blockSize)) {
int i = inputFile.gcount();
//Do stuff
}
Suppose our block size is 1024 bytes, and the file is 24,3 KiB. After reading the 23rd block, there will be 0,3 KiB left to r... | I think that Konrad Rudolf who you talk about in the comment to another answer makes a good point about the problem with reading until eof. If you never reach eof because of some other error you are in an infinite loop. So take his advice, but modify it to address the problem you have identified. One way of doing it is... |
6,449,266 | 6,449,296 | Can input iterators be used where forward iterators are expected? | To my knowledge, the hierarchy of iterator categories goes like this:
Random access -> Bi-directional -> Forward -> Input
-> Output
Correct?
I always thought there was a rule, that if an algorithm expects a particular type of iterator, you can provide iterators of categories ... |
Can input iterators be used where forward iterators are expected?
No. The difference between an input iterator and a forward iterator is that an input iterator is a "single-pass" iterator but a forward iterator is a "multi-pass" iterator.
Once you advance an input iterator, you can no longer access the previous ele... |
6,449,332 | 6,449,398 | Increasing C++ Program CPU Use | I have a program written in C++ that runs a number of for loops per second without using anything that would make it wait for any reason. It consistently uses 2-10% of the CPU. Is there any way to force it to use more of the CPU and do a greater number of calculations without making the program more complex? Additional... | Assuming your application has the power (PROCESS_SET_INFORMATION access right), you can use SetPriorityClass to bump up your priortiy (to the usual detriment of all other processes, of course).
You can go ABOVE_NORMAL_PRIORITY_CLASS (try this one first), HIGH_PRIORITY_CLASS (be very careful with this one) or REALTIME_P... |
6,449,343 | 6,449,372 | Using shared memory with fork() | I already looked at the only similar post I could find, but it wasn't what I was looking for.
Basically, I'm trying to run the Odd-Even Sort with forking, so the child runs odds and parent runs the evens. These both require the sharing of the vector inputValues, as well as the boolean sorted.
The following code is with... | You're going to have to use shmget() and shmat() to setup a shared memory object, but unfortunately that won't be a dynamic memory object like a std::vector. In other words, you'll have to declare the entire size of the object at the point of initialization of the shared memory object. The process though is pretty st... |
6,449,566 | 6,460,187 | I can no longer build and run in Xcode 3 | I checked to see if the terminal recognized g++/gcc and it did, but I can't build and run in xcode. Every time I try to do it I get this...
Xcode used to build and run properly on my computer and then I reinstalled xcode to get some extra features that I didn't have (iOS SDK). Also, I wanted to fix this problem.
Befo... | The problem was that I didn't have a gcc-4.2 and g++-4.2 in /Developer/usr/bin. Instead I had i686-apple-darwin10-g++-4.2 and i686-apple-darwin10-gcc-4.2 and a bunch of other similar files, which I thought were the same thing as gcc-4.2/g++4.2. Apparently I could still compile and run in the shell with this, but Xcode... |
6,449,670 | 6,449,693 | how to get current PAM user in pam_ldap? | how can I get the user name that auth by pam_ldap in C/c++?
I found "pam_get_user" API, but how can I get the pam_handle_t for this function?
Thanks
Dma
| You get the handle by calling:
int pam_start(const char *service_name, const char *user,
const struct pam_conv *pam_conversation, pam_handle_t **pamh);
pamh - is an output parameter in above api.
Check more details here.
|
6,449,745 | 6,501,450 | GPU access on Windows Mobile | I am building an app for Windows Mobile 6.5 and I was wondering if there is any way to hardware accelerate various calculations. I would like to have the GPU do some of the work for the app, instead of relying on the CPU to do everything.
I would like to use C#, but if that is not possible, then C++ is just fine.
Than... | To fully answer your question I would need more details about what calculations you are trying to perform, but the short answer is no, the GPUs in Windows Mobile devices and the SDK Microsoft exposes are not suitable for GPGPU(General-Purpose Computation on Graphics Hardware).
GPGPU really only became practical when GP... |
6,449,831 | 6,449,886 | How do I catch an exception caused from std::map? | I have declared a map like this
map<long long, list<SoundInfo *> > m_soundListMap;
and I also have this function
void addSoundInfo(long long deviceId, SoundInfo * info)
I am trying to add sound info associate with the device id as the key into the map. In this function, I assumed that a key and value pair has been a... |
What is going to happen if I try to get the list and the map doesn't have the key?
Depends on how you try to get the item.
list<SoundInfo*>& info_list = m_soundListMap[55];
Will create an empty list, insert it into the map and return that when the key doesn't exist yet.
typedef map<long long, list<SoundInfo *> >::it... |
6,449,935 | 6,449,951 | Increment void pointer by one byte? by two? | I have a void pointer called ptr. I want to increment this value by a number of bytes. Is there a way to do this?
Please note that I want to do this in-place without creating any more variables.
Could I do something like ptr = (void *)(++((char *) ptr)); ?
| You cannot perform arithmetic on a void pointer because pointer arithmetic is defined in terms of the size of the pointed-to object.
You can, however, cast the pointer to a char*, do arithmetic on that pointer, and then convert it back to a void*:
void* p = /* get a pointer somehow */;
// In C++:
p = static_cast<char*... |
6,449,997 | 6,453,484 | Why is it thought of 'T *name' to be the C way and 'T* name' to be the C++ way? | Note: This question is about the position of the asterisk (*).
In most C code I see (e.g., in Beej's guide to network programming), all variable declarations / definitions use the T *name format, i.e., bind the * to the variable name. The pointer is thought of belonging to the variable, not the type.
In most C++ code I... | From Stroustrup's C++ Style and Technique FAQ.
A "typical C programmer" writes int *p; and explains it "*p is what is the int" emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.
A "typical C++ programmer... |
6,450,403 | 6,450,573 | C++ Multithread functions with inclusive and exclusive in Linux and Windows | Linux
I have two functions: functionA and functionB
These two functions can be ran multithreaded, which:
There is at most one functionA can be ran at a time
There may be many functionB(s) can be ran at a time
functionA and functionB are exclusive, i.e if functionA is being excuted
then functionB must wait until functi... | You can use boost to create a read-write lock:
#include <boost/thread/locks.hpp>
typedef boost::shared_mutex Lock;
typedef boost::unique_lock< boost::shared_mutex > WrtieLock;
typedef boost::shared_lock< boost::shared_mutex > ReadLock;
Lock myLock;
void ReadFunction()
{
ReadLock r_lock(myLock);
//Do reader... |
6,450,544 | 6,450,564 | How do I call local function from a static function? | #ifndef DATACENTER_H_
#define DATACENTER_H_
#include <map>
#include <list>
#include <string>
#include "LiLo/SoundInfo.h"
#include "MutexCondition.h"
#include "UserInfo.h"
using namespace std;
class DataCenter : MutexCondition{
private:
map<long long, list<SoundInfo *> > m_soundListMap;
void add(long lon... | If you want to access addSoundInfo from other classes, you need to make it public, or make those other classes friends of DataCenter. static has nothing to with access control.
A static function is not bound to an instance of the class it belongs to, and thus can not access members of that class (it also can not call m... |
6,450,753 | 6,450,763 | C++ Multithread with global variables | Anyone know whether primitive global variable is thread safe or not?
// global variable
int count = 0;
void thread1()
{
count++;
}
void thread2()
{
count--;
if (count == 0) print("Stuff thing");
}
Can I do it this way without any lock protection for count?
Thank you.
| This is not threadsafe. You have a race-condition here. The reason for that is, that count++ is not necessarily atomic (means not a single processor operation). The value is first loaded, then incremented, and then written back. Between each of these steps, the other thread can also modify the value.
|
6,450,786 | 6,450,878 | How to make large calculations program faster | I'm implementing a compression algorithm. Thing is, it is taking a second for a 20 Kib files, so that's not acceptable. I think it's slow because of the calculations.
I need suggestions on how to make it faster. I have some tips already, like shifting bits instead of multiplying, but I really want to be sure of which ... | The question of how to make things faster should not be asked here to other people, but rather in your environment to a profiler. Use the profiler to determine where most of the time is spent, and that will hint you into which operations need to be improved, then if you don't know how to do it, ask about specific opera... |
6,450,830 | 6,476,584 | Custom command to generate object(.o) from binary file using autoconf | We have a project (c++) and it needs to include a binary file into shared library. This is done on windows by referencing the binary file from a resource file. On Linux it can be achieved by using objcopy as shown here
The question is how can this be automated this using autoconf/automake? There exists Makefile.am and ... | Does your binary file have a distinctive extension? If so, refer to the Suffixes chapter of the manual:
.bin.o:
bin2o -o $@ $<
And you then list foo.bin in your foo_SOURCES variable.
If you don't have a distinctive extension, try something like this:
foo_SOURCES = foo.c bar.c baz.c
foo_LDADD = foobin$(OBJEXT)
... |
6,451,560 | 6,451,574 | C++: More and more complex bugs misleading the debugger | It seems like the bugs in my project are evolving. While in the beginning time, causers of program crashes were easily to spot using the debugger (the line it points to after the program crashes), it's different now.
Many bugs cause the program to crash in completely arbitary places not even closely related to them.
H... | Profile your code for memory corruption, memory overwrites and memory leaks.
|
6,451,866 | 6,451,911 | Why use functors over functions? | Compare
double average = CalculateAverage(values.begin(), values.end());
with
double average = std::for_each(values.begin(), values.end(), CalculateAverage());
What are the benefits of using a functor over a function? Isn't the first a lot easier to read (even before the implementation is added)?
Assume the functor ... | At least four good reasons:
Separation of concerns
In your particular example, the functor-based approach has the advantage of separating the iteration logic from the average-calculation logic. So you can use your functor in other situations (think about all the other algorithms in the STL), and you can use other func... |
6,452,182 | 6,452,251 | EXC_BAD_ACCESS signal when trying to initialize __m128 class member variable | I'm using Apple GCC 4.2.1 and I've stumbled upon a strange problem with the following code... I always get EXC_BAD_ACCESS exception when trying to initialize __m128 class member variable. Unfortunately the following simplified code works in a test application, but maybe you can still help me locate the root of this pro... | From the top of my mind: i'd say alignment issues
Especially, the part where it says 'lot's of members'
Look at __attribute__ aligned
Are stack variables aligned by the GCC __attribute__((aligned(x)))?
http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Variable-Attributes.html#Variable-Attributes
|
6,452,384 | 6,452,490 | Naming Array Elements, or Struct And Array Within a Union | Consider the following struct:
struct Vector4D
{
union
{
double components[4];
struct { double x, y, z, t; } Endpoint;
};
};
It seems to me that I have seen something similar in WinApi's IPAddress struct. The idea is to give me the possibility to use the array components both by index and by name,... |
yes
depends on the alignment needs of the architecture and the compilers strategy
no, but you could make a object wrapper (but you will end up with .z() instead of just .z)
Most compilers should support squashing a structure using a pragma or an attribute. #pragma pack for example.
|
6,452,385 | 6,452,436 | New implementation of a library function and calling the old implementation within that | I want to implement some custom library functions in Linux. For example, I want to implement my own pthread_mutex_lock, pthread_mutex_unlock, malloc and free functions. I've read LD_PRELOAD can be used to use your own custom functions, although I haven't got into the details.
But I have one question, I also want to us... | You could use the dlopen function to open the library you replace (or use RTLD_NEXT if it is already loaded, see comments), and then use dlsym function to find the address of the function in that library that you want to call.
|
6,452,580 | 6,452,631 | Calling CloseHandle after calling SetEvent | I have a thread running in my application. Inside the thread I am waiting on an auto reset event to exit. I want to make sure that i close the handle of the event after i use it. Ihave two options.
Calling CloseHandle of the event immediately after calling SetEvent
Calling CloseHandle after the line WaitForSingleObjec... | Calling CloseHandle after SetEvent doesn't make sense to me. You should (if required) call CloseHandle after WaitForSingleObject only.
|
6,452,756 | 8,407,739 | Exception running boost asio ssl example | I'm trying to run the SSL examples from boost::asio and I'm getting an "Invalid argument" exception when I run them. I'm on Linux x86_64.
http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio/example/ssl/client.cpp
http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio/example/ssl/server.cpp
Compiled with:
g++ ser... | OK, for anyone finding this in the future, you need to create your certificates and sign them appropriately.
Here are the commands for linux:
//Generate a private key
openssl genrsa -des3 -out server.key 1024
//Generate Certificate signing request
openssl req -new -key server.key -out server.csr
//Sign certificate wi... |
6,452,826 | 6,453,939 | xsubpp c++ exceptions | xsubpp can generate exception handling code for c/c++ files converted from .xs files. It generates the following piece of code for me
TRY {
char * CLASS = (char *)SvPV_nolen(ST(0));
Example * RETVAL;
RETVAL = new Example();
ST(0) = sv_newmortal();
sv_setref_pv( ST(0), CLASS, (void*)RETVAL );
}
... | This falls into the "well don't do that then" category. (The canonical answer to "Doctor, it hurts when I do X"). Look at the generated code:
CATCHALL
sprintf(errbuf, "%s: %s\tpropagated", Xname, Xreason);
ENDHANDLERS
This isn't propagating the exception. It is printing a message and then utterly ignoring the fact... |
6,452,987 | 6,453,464 | Create LLVM bytecode from C++ classes | I'm writing a compiler for a special purpose language in LLVM. I want to add bindings for a library that is already written in C++. My idea is to compile the library to LLVM bytecode (using clang -emit-llvm -S abc.c) and link it during compilation. This works well for code like
// lib.c
int f() {
return 123;
}
But... | You could see whether clang honours external linkage for explicit template instantiations. This might apply to non-templates, but otherwise you could 'force it' to work for templates.
Simple synopsis:
lib1.h
template <typename T=int>
struct ATemplate { T f() { return 123; } };
add a file lib1_instantiate.cpp
#include ... |
6,453,084 | 6,454,075 | How to terminate worker thread properly in an injected DLL? | I'm injecting a DLL into some process, the DLL has a worker thread that is running a message loop.
I'd like to quit the thread properly i.e. post a quit message (PostThreadMessage) and wait for it (WaitForSingleObject).
Where can i wait for this thread to close? I can't do it on DLL_PROCESS_DETACH because by then a... | If you need to perform some action on "About-To-Close" you need to hook the main thread using SetWindowsHookEx with WH_CALLWNDPROC and look for WM_CLOSE and take action/signal the thread to close.
|
6,453,543 | 6,453,675 | C++: Reading Binary Files | I have a Binary file that has several names followed by some details (50 bytes fixed). Each name is followed by 0X00 followed by the 50 byte details. I need to extract just the names from the file. i.e read all characters till 0x00, skip 50 bytes and continue till end of file.What is the best way to do it in C++.
| #include <fstream>
#include <string>
...
std::ifstream file("filename");
if ( ! file.is_open() )
return;
std::string name;
char data[50];
while ( std::getline( file, name, '\0' ) && file.read( data, 50 ) )
{
// you could use name and data
}
file.close();
...
|
6,453,569 | 6,453,637 | reference to element in boost.fusion vector | EDIT - please ignore - the question resolved around a simple typo. I need a break.
How do I access a reference to an element of a boost fusion vector?
Unlike boost.tuples's tuples::get<i>(variable) (returns a reference), the fusion::at_c<i>(variable) returns a constant and this causing me difficulties.
The following il... | Can't you just do fusion::at_c<0>(vec) = 2;?
|
6,454,107 | 6,454,147 | Opening Unicode filenames in windows from DOS 8.3 filenames | Can I generate a 8.3 filename for a unicode filename and use that ASCII string of char's to open an fstream in Windows?
I know that MSVC++ provides a wchar_t* overload for fstream, but GCC's libstdc++ does not provide this :(, so I need an alternative. I don't want to create my own streambuf class just for this, as it ... | You can probably leverage the Windows API function GetShortPathName to give you the short name. You cannot "compute" the name algorithmically as there is no one-to-one correspondence between an arbitrary long name and a short name, and I don't think you can avoid using the Windows API for the translation.
|
6,454,281 | 6,454,306 | C++ STL: list with Pointers - Iterator cannot access? | I am struggeling with an STL list that holds Pointers of my "Object" object.
I declared:
list<Object*> objectlist;
and inserted via:
this->objectlist.push_back(new Object(address,value,profit));
and tried to iterate like in maps and others:
list<Object*>::iterator iter;
iter = this->objectlist.begin();
while(iter !... | You need (*iter)->print();
Since you have an iterator to a pointer, you have to first de-reference the iterator (which gets you the Object*) then the arrow de-references the Object * and allows the call to print.
|
6,454,411 | 6,456,348 | "term does not evaluate to a function taking ..." in a global object | I think this problem is a bit beyond me. I'd appreciate any help.
In UIM_Commander.cpp, I need to use a (static) method from the class UIM_Parser. So, in UIM_Commander.h, I included UIM_Parser.h, like so:
#ifndef UIM_Commander_h
#define UIM_Commander_h
#include "..\sysm\SYSM.h"
#include "..\storm\STORM.h"
#include "..... | You could forward declare UIM_Commander in UIM_Parser.h, and keep your includes together..
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.