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 |
|---|---|---|---|---|
4,618,523 | 4,618,769 | Template specialization of templated type not selected when using multiple typenames | Let's say I have
template <typename T>
class F;
I can create another template who takes an F as a type, with a default and a specialization.
template <typename S>
class G;
template <>
template <typename T>
class G <F<T> >
{
};
I can instantiate G<F<int> > g_of_f. The compiler correctly selects the specialization of ... | The template<> syntax is used to introduce an explicit specialization declaration, what you have here are partial specializations :
template <typename S>
class G;
template <typename S>
class G < F<S> >
{
};
template <typename U, typename S>
class H;
template <typename U, typename S>
class H <U, F<S> >
{
};
|
4,618,586 | 4,618,610 | c++ create a pointer to new class | i have problem withe this code i want to create a pointer to new class
class AnalyzerManager
{
public:
AnalyzerManager();
~AnalyzerManager();
private:
CAnalyzerIF* m_AnalyzerIF = new CAnalyzerIF();
};
it has a compilation error i dont understand how to fix it.
thanks
| You have to initialize the pointer in your constructor, not in the class declaration.
AnalyzerManager::AnalyzerManager() : m_AnalyzerIF(new CAnalyzerIF())
{
}
BTW, you might want to look into smart pointers for something like this.
|
4,618,606 | 8,696,176 | How can I use use C++ to send data through a websocket? | I want to be able to send data over a websocket in my C++ code? Is there some library or standard way that this is done? Thanks for the help, I appreciate it, and please let me know if I should provide more information.
| Please have a look at https://github.com/zaphoyd/websocketpp,
which is based on Boost ASIO.
You can find a comparison of websocket implementations at
http://en.wikipedia.org/wiki/Comparison_of_WebSocket_implementations.
|
4,618,826 | 4,623,154 | Measuring device drivers CPU/IO utilization caused by my program | Sometimes code can utilize device drivers up to the point where the system is unresponsive.
Lately I've optimized a WIN32/VC++ code which made the system almost unresponsive. The CPU usage, however, was very low. The reason was 1000's of creations and destruction of GDI objects (pens, brushes, etc.). Once I refactored ... | You can use various tools from SysInternals Utilities (now a Microsoft product, see http://technet.microsoft.com/en-us/sysinternals/bb545027) to give a basic idea before jumping in. In your case process explorer (procexp) and process monitor (procmon) performs a decent job. They can be used to get you a basic idea ab... |
4,618,901 | 4,619,044 | multiple declaration error- virtual functions | I have observer.h , client.h and field.h files.
In observer.h there is Subject class which has
// observer.h
class Subject {
public:
virtual ~Subject(){};
Subject(){};
virtual void Attach(Observer*);
virtual void Detach(Observer*);
virtual void Notify(bool _value);
virtual bool getCheckedIn(){};
private:
vec... | We can't actually see it here, but the problem is probably that you defined Subject::notify(bool) in a header file (your observer.h just declares it, it doesn't define it) and you included that header file in both Field.cpp and main.cpp, so you get multiple definitions. The fix is to move the definition into a source ... |
4,618,986 | 4,619,431 | c++ switch access violation | what i'm writing is simple, well, it should be, but i'm getting this error and i don't know what else to do, my code look like this
int main()
{
char *option;
while(strcmp(option,"exit")!=0){
int opt = GetSystemDefaultUILanguage();
std::string lang;
switch(opt)
{
... | Your program will always get an access violation because of the following lines:
char *option;
while(strcmp(option,"exit")!=0){
std::cin>>option;
You never initialize the pointer option, but then try to use it. Change your code to this:
int main()
{
std::string option;
while(option != "exit")
{
... |
4,619,101 | 4,636,175 | xcode include paths conflicts | In MSVS when I #include <someHeader> it is searched in a different folder than the headers included with #include "someheader". Same thing should be in xcode, but it seems that it does not work. Because of this I have conflicts with local headers that have same name as std headers(String.h, etc) and I can't include std... | I solved the problem by changing all headers extension from h to hpp... It's not a real solution, but I kept the file names and I solved the problem, for now:)
|
4,619,502 | 4,619,862 | boost::asio error "The I/O operation has been aborted..." | I am receiving this error message
"The I/O operation has been aborted because of either a thread exit or an application request"
when using boost::asio::socket::async_read_some()
What does the error mean? What should I be looking for?
Here is the relevant code:
void tcp_connection::start()
{
printf("Connected to sim... | Your tcp_connection object or your buffer object is likely going out of scope prior to the async operation completing.
Since your program is based on one of the tutorial examples, why don't you check out another of the examples that reads some data as well: http://www.boost.org/doc/libs/1_45_0/doc/html/boost_asio/examp... |
4,619,633 | 4,619,676 | Base class template instantiation depending on derived class constructor argument type | In the following, shouldn't base class constructor be generated by the compiler based on derived class constructor argument type?
template <class T>
class foo
{
int a;
public:
foo(T a){}
// When I convert the constructor to a function template, it works fine.
// template <typename T> foo(T a){}
};
class ba... | The syntax in class bar : public foo<class T> is incorrect.
Either bar depends on a template parameter T and bar should be a template :
template<class T>
class bar : public foo<T>
{
public:
bar(int a):foo(a){}
};
int main()
{
bar<int> obj(10);
}
Or you want bar to inherit from a specific instantiation of fo... |
4,619,719 | 4,619,762 | boost.parameter and constructors | In the documentation: http://www.boost.org/doc/libs/1_45_0/libs/parameter/doc/html/index.html#parameter-enabled-constructors
Do I understand correctly, that I can't use parameter names without using base-class, as shown in the example?
Because macro BOOST_PARAMETER_CONSTRUCTOR, as the second argument requires the name ... | Yes, that would be correct. 123
|
4,619,791 | 4,619,846 | Public and private inheritance in C++ | As we know from the literature for the public inheritance the object of child class (sub-class) also can be considered as the object of base class (super-class). Why the object of the sub-class can’t be considered as an object of super-class, when the inheritance is protected or private?
| Because you can't see it:
class Base
{
public: virtual ~Base() {}
};
class PublicDerived: public Base
{ };
class PrivateDerived: private Base
{ };
int main()
{
PublicDerived publicD;
PrivateDerived privateD;
Base& base1 = publicD;
Base& base2 = privateD; // ERROR
}
... |
4,620,016 | 4,620,537 | Boost.Spirit.Qi: Take a rule's attribute and set it as a field of an enclosing rule's struct attribute? | Like, many of these other questions, I'm trying to parse a simple grammar into a tree of structs using Boost.Spirit.Qi.
I'll try to distill what I'm trying to do to the simplest possible case. I have:
struct Integer {
int value;
};
BOOST_FUSION_ADAPT_STRUCT(Integer, (int, value))
Later, inside of a grammar struct, I... | If Integer is supposed to be the attribute exposed by the rule, you need to declare it as:
qi::rule<Iterator, Integer()> integer;
(note the parenthesis). Spirit requires to use the function declaration syntax to describe the rule's 'interface'. It is used not only in Spirit but by several other libraries as well (see... |
4,620,105 | 4,620,333 | Qt non-static linking and .pro files | I am trying to build a .dll that uses the QtCore4 and QtGui4 .dll files. However, I want both Qt .dll files to be linked non-statically. I have read a lot about .pro files and static linking but no one seems to talk about dynamic linking with Qt .dll's. How do I ensure that the qt dlls are built for dynamic linking?
I ... | Unless you added the keyword 'static' to your configuration parameters, the Qt libraries should be already building as dynamic link libraries. That is the default configuration.
|
4,620,920 | 4,621,037 | How can I add more objects of a class to a vector without doing dynamic memory allocation? | class AClass
{
// ...
}
~
class AnotherClass
{
public:
// ...
void AMethod()
{
// ...
AClass * ac = new AClass(); // Dynamic memory allocation here
m_Objects.push_back(ac);
// ...
}
// ...
private:
// ...
... | There are two things causing dynamic memory allocations here:
vector::push_back
new AClass()
Here is one idea how to reduce dynamic memory allocations.
First step is to call m_Objects.reserve(N); in the AnotherClass constructor, where N is the maximum number of AClass objects you want to keep at any given time. This ... |
4,621,191 | 4,621,202 | C++ random number 1-9 | I need random numbers from 1 to 9 (without 0).
//numbers 0 to 9
int iRand = rand() % 10;
But I need 1 to 9.
Thanks.
| Just this:
int iRand = (rand() % 9) + 1;
|
4,621,342 | 4,635,889 | SSE4 inline assembly problems in C++ | Hello Everyone
I want to execute an inline assembly instruction that is of the following form
BLENDPD xmm1,xmm2/m128, imm8
I am new to inline assembly so i am having some difficulties.
my code is:
#include<iostream>
using namespace std;
int main()
{
long long y;
__asm("blendpd %0,$0xabcd000000001111abcd0000000011... | As an alternate answer to my other answer, here's how to do this with inline assembly rather than an intrinsic. (As Thomas Pornin notes on my other answer, intrinsics are generally better because they're more portable, but sometimes you want something like this too.)
First, I cheated -- I took the version with an intr... |
4,621,547 | 4,621,590 | Multi-threaded Pooled Allocators | I'm having some issues using pooled memory allocators for std::list objects in a multi-threaded application.
The part of the code I'm concerned with runs each thread function in isolation (i.e. there is no communication or synchronization between threads) and therefore I'd like to setup separate memory pools for each t... | Why not just construct an instance of local_alloc with a reference to make_quadtree?
|
4,621,642 | 4,622,271 | Getting QInputDialog::getText() result from C code running in non-GUI thread | I have previously solved a similar problem in this question, where I asked how to display a QMessageBox from a non-GUI thread in Qt running C code.
The solution I was suggested, to use signals & slots and a Qt::QueuedConnection to connect a signal that could be emitted by the C code calling a C++ function that in turn ... | It ought to work if you use QString* instead of QString&. You may have to also register QString* as a metatype - or, if you can't be bothered doing that, use void* instead and cast back and forth.
|
4,621,731 | 4,621,832 | C or C++ to write a compiler? | I want to write a compiler for a custom markup language, I want to get optimum performance and I also want to have a good scalable design.
Multi-paradigm programming language (C++) is more suitable to implement modern design patterns, but I think that will degrade performance a little bit (think of RTTI for example) wh... | The "expensive" features of C++ (e.g., exceptions, virtual functions, RTTI) simply don't exist in C. By the time you simulate them in C, you're likely to end up with something at least as expensive as it is in C++, but less known, less documented, etc. (let's face it: compiler writers aren't stupid -- while it's possib... |
4,621,844 | 4,638,230 | Cross Correlation of two arrays in OpenCV | Is there a way to calculate the normalized cross correlation of two arrays in OpenCV (C++)?
http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/correlate/
I have a CvMat and I want to get a correlation matrix of all the cols.
I saw cvCalcCovarMatrix but I can't see a way to normalize it to get the correlation.
| You should use cvMatchTemplate() with method=CV_TM_CCORR_NORMED.
|
4,621,905 | 4,621,919 | Defining names in place of "true" and "false" for bool type | I am wanting to use a bool to switch back and forth between loading X and loading Y from a file. I don't want to use "true" and "false", because it doesn't make the code clear. I would rather use something like LOAD_X or LOAD_Y... Is the following code the way to do it? Or is there a better way?
#define LOAD_X true
#de... | I would use an enum instead. Just because there are two choices, doesn't mean the type should be bool
enum load_type { loadX, loadY };
|
4,622,225 | 4,622,239 | Aren't Boolean variables always false by default? | I had declared a Boolean variable bool abc; in a class and thought that it would be false by default. An if condition in my program, if (abc), turned out to be true, so I output the value of abc, and saw that it contained the value 55. Is this normal?
Do we always have to assign 'bool abc=false' to be sure that it is f... | Yes, you should always initialize your variables. Until you intimately learn the times when it is and isn't necessary to do so explicitly, you should do it all the time, no matter what. And by then...well...why stop a good habit?
To initialize a bool to false it's sufficient to default construct it:
struct X
{
bool... |
4,622,330 | 4,622,467 | Operator overloading : member function vs. non-member function? | I read that an overloaded operator declared as member function is asymmetric because it can have only one parameter and the other parameter passed automatically is the this pointer. So no standard exists to compare them. On the other hand, overloaded operator declared as a friend is symmetric because we pass two argume... | If you define your operator overloaded function as member function, then the compiler translates expressions like s1 + s2 into s1.operator+(s2). That means, the operator overloaded member function gets invoked on the first operand. That is how member functions work!
But what if the first operand is not a class? There's... |
4,622,433 | 4,622,634 | How FB created FBML? | I am really interested in how FB created FBML and how to go about creating something similar. Did they write a C++ processor that replaces FBML with HTML or do they use XSLT or what did they do to create a templating language like that? I am wanting to do this mainly for my own knowledge and fun on my spare time to see... | Well, there are 3 ways to write a parser for XML that converts to HTML:
write a parser in lex and bison
use an XML parser library to read the XML into memory, and us a "normal" programming language to convert the XML to HTML.
use XSLT
use some web framework that supports custom tag libraries that can convert the FBM... |
4,622,461 | 4,622,481 | Difference Between *(Pointer + Index) and Pointer[] | int* myPointer = new int[100];
// ...
int firstValue = *(myPointer + 0);
int secondValue = myPointer[1];
Is there any functional difference between *(myPointer + index) and myPointer[index]? Which is considered better practice?
| Functionally, they are identical.
Semantically, the pointer dereference says "Here's a thing, but I really care about the thing X spaces over", while the array access says "Here's a bunch of things, I care about the Xth one."
In most cases, I would prefer the array form.
|
4,622,516 | 4,622,537 | Sorting std::strings with numbers in them? | I'm currently sorting by the std::string < operator. The problem with it is that:
30 < 9. The 30 shows up before the 9 since 3 < 9, Windows 9x had this issue to. How could I go about sorting them numerically so that "30 Foxes" shows up after "9 dogs". I should also add that I'm using utf 8 encoding.
Thanks
| You can create a custom comparison function to use with std::sort. This function would have to check if the string begins with a numeric value. If it does, convert the numeric part of each string to an int using some mechanism like a stringstream. Then compare the two integer values. If the values compare equally, ... |
4,622,535 | 4,622,756 | Arduino Ethernet Byte size problem | I'm using an Arduino (duemilanove) with the official Ethernet shield to send data to the controller for controlling an LED matrix. I am trying to send some raw 32-bit unsigned int values (unix timestamps) to the controller by taking the 4 bytes in the 32-bit value on the desktop and sending it to the arduino as 4 cons... | 63 is the ASCII code for ?. There's some relevance to the values, ASCII doesn't have character codes for values over 127. An ASCII encoder commonly replaces invalid codes like this with a question mark. Default behavior for the .NET Encoding.ASCII encoder for example.
It isn't exactly clear where that might happen. ... |
4,622,647 | 4,622,806 | TIL that variable can be defined like a function call in C++ | I am new to C++.
While I was going through C++ materials, I found that variables in C++ can be defined similar to function calls.
i.e.
int var = 10; //explicit assignment
is same as,
int var(10); //implicit assignment
"Even though implicit assignments look a lot like function calls, the compiler keeps track of which... | it looks more like a constructor call than a function call actually ;) this is useful when members of a class are given values during object construction. let me give an example:
#include <iostream>
class Cool
{
public:
Cool(std::string someString, bool isCool);
~Cool();
std::string getSome... |
4,622,673 | 4,622,703 | converting source code from window to linux | c++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
I am converting some source code from windows to running on ubuntu.
However, the windows is using the code below to log messages and get the current time the message is logged. However, this is windows. What is the best way to convert this to running on linux?
struct _timeb t... | in linux a similar function ftime is used which gives you the time do
#include <sys/timeb.h>
/* .... */
struct timeb tp;
ftime(&tp);
printf("time = %ld.%d\n",tp.time,tp.millitm);
this will give you the time in second and milliseconds.
|
4,622,693 | 4,622,710 | Issuing system commands in Linux from C, C++ | I know that in a DOS/Windows application, you can issue system commands from code using lines like:
system("pause");
or
system("myProgram.exe");
...from stdlib.h. Is there a similar Linux command, and if so which header file would I find it in?
Also, is this considered bad programming practice? I am considering tryin... | Not surprisingly, the command is still
system("whatever");
and the header is still stdlib.h. That header file's name means "standard library", which means it's on every standard platform that supports C.
And yes, calling system() is often a bad idea. There are usually more programmatic ways of doing things.
If you wan... |
4,622,844 | 4,622,854 | virtual keyword in different scenarios | I figured out 2 different situations where virtual is used.
If a baseClass has a function defined virtual, then the derivedClass is going to override the function.
The baseClass::~baseClass() should be defined virtual, if there is any class derived from it. Here it means, the derived class destruction first takes plac... | There's also virtual inheritance, where the base class is referenced by an indirection.
In C++, what is a virtual base class?
|
4,623,364 | 4,623,410 | "undefined reference" when linking against a static library | g++ (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5
I have the following static library called sdpAPI.a. I am having problems trying to link it with my test application. Just wondering if I am doing something wrong. The static library has been built with g++;
My directory is as follows:
/projects/unit_test/main.c
/projects/unit_... | -L specifies the library path, not a specific library. You probably want -L sdp/lib -l sdpAPI to specify both the path and the library name.
Although it will try to prefix and postfix your library name with lib and either .a or .sl (or similar).
So you may also need to rename your library to libsdpAPI.a as per the gcc ... |
4,623,452 | 4,623,534 | The use of enum without a variable name | I understand the first one but the second one? When and why would you do that?
enum cartoon { HOMER, MARGE, BART, LISA, MAGGIE };
enum { HOMER, MARGE, BART, LISA, MAGGIE };
| you can define such enum in a class, which gives it a scope, and helps expose class's capabilities, e.g.
class Encryption {
public:
enum { DEFAUTL_KEYLEN=16, SHORT_KEYLEN=8, LONG_KEYLEN=32 };
// ...
};
byte key[Encryption::DEFAUTL_KEYLEN];
|
4,623,465 | 4,623,506 | Virtual difference syntax C++ | With C++, virtual is used like this? What's the difference between the both?
class Animal
{
public:
virtual void something();
virtual void something() = 0;
}
| I might be fuzzy on this but I think the first says: You can override me, and the second says, You must override me.
|
4,623,527 | 4,623,569 | Can someone explain this C/C++ syntax? | Can sombody explain how this works?
int x, y;
....
(some_condition ? x : y) = 100;
Is this intended to work or is is just a "blind" translation or the compiler (something like vec[10] equals 10[vec])?
| This is valid C++ and invalid C.
The result of a conditional expression can be (and in this case is) an lvalue in C++ refering to one of x or y depending on whether some_condition evaluates to true. In C++ either x is assigned the value 100 if some_condition is true when converted to a bool, otherwise y is assigned 100... |
4,623,604 | 4,623,619 | C++ Pointer (Pass By Reference) Question | A pointer that is passed-in-by-reference. Why? aren't pointers just references anyways? What's really happening to this parameter?
void someFunc(MyPtr*& Object)
{
}
| Simply speaking, it gives you the ability to change the pointer itself: it can be changed to point to another location in the function.
And the change will be reflected outside.
|
4,623,610 | 4,623,669 | C++: value_type versus make_pair, which is faster for map insert? | typedef map<KeyType, ValType> KVMap;
KVMap kvmap;
kvmap.insert( KVMap::value_type( key, val ) );
kvmap.insert( make_pair( key, val ) );
Which of the above options to insert to a STL map is always faster? Why?
Note: I am well aware that insert() is faster than using []= for adding (not updating) key-value pairs to a m... | Chances are that the first will be 'epsilon-faster', because of this (from 23.3.1 in the standard) :
typedef pair<const Key, T> value_type;
[...]
pair<iterator, bool> insert(const value_type& x);
In the first version, you directly construct the appropriate type expected by std::map<K,V>::insert
In the second versi... |
4,623,676 | 4,623,724 | C++ Variable array in a Class Problem | I was wondering if there was a way to include a data member which is an array of unfixed size.
The function initModulation will create an int array of size M and a Complex array of size M. (Complex is another class and is made up of a real component and imaginary component).
The function modulate will need to be able t... |
Don't write initialization functions without very special circumstances; construct with the constructor.
The arrays are logical part of the class data, since they are used for modulation, and that's what instances of the class do. So you should have them as members.
You were planning to create arrays of unknown-at-com... |
4,623,835 | 4,623,979 | Use of derived class construction when derived class object is type compatible with base class | class baseClass{};
class derivedClass : public baseClass{};
baseClass *obj = new derivedClass ; // For simplicity, I amn't providing any-
// class members.
Though, baseClass and derivedClass construction takes place, derivedClass members are opaque to obj. Then, what is the ... | In a word, polymorphism. In more words, in a system where multiple classes are derived from a common base class it's the ability to treat objects of different derived classes in the same way, without worrying about their actual type.
Consider a drawing package that manages various shapes. You may choose to use an abstr... |
4,623,963 | 49,777,806 | Empty Data Member Optimization: would it be possible? | In C++, most of the optimizations are derived from the as-if rule. That is, as long as the program behaves as-if no optimization had taken place, then they are valid.
The Empty Base Optimization is one such trick: in some conditions, if the base class is empty (does not have any non-static data member), then the compil... | It is coming to c++20 with the [[no_unique_address]] attribute.
The proposal P0840r2 has been accepted into the draft standard. It has this example:
template<typename Key, typename Value, typename Hash, typename Pred, typename Allocator>
class hash_map {
[[no_unique_address]] Hash hasher;
[[no_unique_address]] Pred... |
4,624,132 | 4,624,291 | why cannot use uncaught_exception in dtor? | Herb Sutter in his article http://www.gotw.ca/gotw/047.htm
pointed out that we cannot use uncaught_exception in desturctor function,
// Why the wrong solution is wrong
//
U::~U() {
try {
T t;
// do work
} catch( ... ) {
// clean up
}
}
If a U object is destroyed due to stack unwinding during to ex... | This is exactly what he meant: "will fail to throw" means "will not throw because it will think that throwing isn't safe in the current context" (not "will crash"; fail here means won't happen). Because the destructor is called as part of the stack-unwinding caused by an exception std::uncaught_exception() returns true... |
4,624,201 | 4,624,552 | setWindowFilePath didn't work in Qt at all | Why setWindowFilePath didn't work? Slot is working. The window title does not change.
My OS is Windows 7, Qt was compiled with wchar_t support.
test::test(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
QObject::connect(ui.pushButton, SIGNAL(clicked()), SLOT(Click()));
setW... | Maybe your problem is that you already used setWindowTitle() before using setWindowFilePath(). From the docs:
If the window title is set at any point, then the window title takes precedence and will be shown instead of the file path string.
Edit: I just tried using setWindowFilePath() and noticed that it only takes e... |
4,624,248 | 4,624,295 | C#. Logical riddle with bit operations. Only one bit is set? | This should be easy for C++ people though. But I was asked how to do it in C#. Shouldnt be much of difference.
How to find out if a long variable has only one bit set?
I cant think anything except some brutal force shifting all bits and counting whats set.
|
A non-negative binary integer value x is a power of 2 if (x&(x-1)) is 0 using 2's complement arithmetic.
Powers of 2 would mean a single bit is set.
http://aggregate.org/MAGIC/#Is%20Power%20of%202
EDIT:
To allow for the zero case:
bool singleBit = x>0 && (x&(x-1))==0
|
4,624,374 | 4,624,396 | create an instance for a pointer in other scopes | I have two methods to create an instance for a pointer.
But one of them will fail.
class A {
public:
int num;
};
void testPointer1(A* a){
a = new A();
a->num = 10;
}
A* testPointer2(){
A* a = new A();
a->num = 10;
return a;
}
void testPointer() {
A* a1 = NULL;
testPointer1(a1); // this ... | The syntax is valid, but it doesn't do what you want because testPointer1() is operating on a copy of the pointer, not the actual pointer itself. So when you assign the address to the newly allocated object, it gets assigned to the copy, not to the original a1 pointer.
Because of this, the address is lost and you get a... |
4,624,490 | 4,624,517 | How to count amount of digits in a given number in c++ | Count amount of digits in a given number or input by the user.
| Independent of programming language:
floor(log10(x))+1
where x is your number (>0).
If you want to handle 0 and negative numbers, I'd suggest something like this:
x == 0 ? 1 : floor(log10(abs(x)))+1
|
4,624,536 | 4,624,821 | Which one will execute faster, if (flag==0) or if (0==flag)? | Interview question: Which one will execute faster, if (flag==0) or if (0==flag)? Why?
| I haven't seen any correct answer yet (and there are already some) caveat: Nawaz did point out the user-defined trap. And I regret my hastily cast upvote on "stupidest question" because it seems that many did not get it right and it gives room for a nice discussion on compiler optimization :)
The answer is:
What is fl... |
4,624,633 | 4,626,549 | Which system calls do these functions make? | Which win32 api calls do these functions use (if any)?
_itoa_s(), strcat_s()
| Only one, really, SetUnhandledExceptionFilter(). Followed by TerminateProcess(). Which is in the code path when the function has detected a buffer overflow. This prevents malware from getting activated by hooking the unhandled exception filter and intentionally causing an access violation. Unfortunately also making... |
4,624,791 | 4,625,026 | QMap::insertMulti or QMultiMap? | What should i use between QMap::insertMulti and QMultiMap to handle :
2 -> abc
2 -> def
3 -> ghi
3 -> jkl
What's the difference enter the 2 solutions ?
| Reading Container Classes:
QMap<Key, T>
This provides a dictionary (associative array) that maps keys of type Key to values of type T. Normally each key is associated with a single value. QMap stores its data in Key order; if order doesn't matter QHash is a faster alternative.
QMultiMap<Key, T>
This is a convenience s... |
4,624,856 | 4,624,879 | Adding delay between shots | Here is the my code, I call the function shooting each loop in main. This results in a lot of a really high rate of fire. I wish to add some delay to get a RoF of maybe 2-3/s but the only way I know how to do it delays my entire loop.
void game::shooting(){
if (P->shoot()){
for(int i=0;i<3;i++){
VGCVector der = V... | if ( NextShootTime < CurrentTime )
{
Shoot();
NextShootTime = CurrentTime + ShootDelay;
}
Initialise NextShootTime to 0 and you're set.
You may also want to handle queuing up multiple bullets in one frame in case the framerate is very low.
|
4,624,865 | 4,625,590 | How to start programming with threads in MFC C++? | i need to create new thread (diffrent class) using cwinthread or afxbeginthreads. i have no idea how to start and which one of them i need to use. help please...
thanks
| There are two types of thread in MFC:
worker threads simply perform a task in the background then exit
user-interface threads which have a message pump i.e. you can PostMessage to it
When I used it in MFC a long time ago I very much disliked not being able to create the class because they force you to do it with thei... |
4,625,184 | 4,625,285 | Passing User Data with SetTimer | I am calling SetTimer in a function of a Class.
SetTimer(NULL, 0, 10000, (TIMERPROC) TimerCallBack);
Where TimerCallBack is:
static VOID CALLBACK TimerCallBack(HWND, UINT, UINT, DWORD)
Now my need is to call one of the method of class which initiated timer, since TimerCallBack is static it has no access to the c... | Obviously, if you were directing timer messages at a window, you could just store the user data with the window.
The only way to do this with a TimerProc is to make a class that manages a statically scoped map of timer-id's to user data objects.
Something like this (As this is a c++ question, Im just implementing a qui... |
4,625,212 | 4,625,409 | class initialization list | Just a simple question about c++ coding style,
for example, all member variables of a class will be called with the default constructor in the initialization list if we don't do anything else. B default constructor will be called and value will be set to 0, int();
class A
{
A();
private:
B b;
int value;
}
How... | It's a good idea to leave the default constructor out. The compiler-generated constructors are much more reliable and maintainable than writing your own versions, and apart from anything else, it's a flat out waste of time to write code the compiler could write for you. If you don't need any construction logic, then do... |
4,625,270 | 4,625,888 | How can I tell if the current process is a service or not (C++, Win32)? | How can I tell if the application my code is running in, is it in a service or an application? Why do I want to know this - I'm writing some code that is injected into the target application and that code has no way of knowing this information up front, so it has to work it out itself.
I cannot rely on any code being c... | Search the current process id (GetCurrentProcessId) from the list of all running services (EnumServicesStatusEx)?
|
4,625,332 | 4,639,040 | StretchBlt and filtering alpha channels | I am scaling an image down with StretchBlt().
http://img684.imageshack.us/img684/2152/stretchblt.png
As you can see, it currently looks like I have to choose between quality filtering and transparency. Is there any way to get both? This is the only image operation I need to perform, so I'd prefer to avoid extra librari... | Gave up entirely on GDI in the end. Turns out that the proper way of doing this is, of course, with IWICImagingFactory. Final code:
IWICImagingFactory *pImgFac;
hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pImgFac));
IWICBitmap* NewBmp;
hr = pImgFac->CreateBitmapFromHBITMAP(... |
4,625,342 | 4,625,388 | How do I pass a "const_reverse_iterator" parameter to "std::vector::erase()"? | std::vector::erase() does not accept reverse iterator.
Is there any way to call this method with a reverse iterator?
My sample code is:
std::vector<int> MyVector;
for (int i=0; i<10; i++)
{
MyVector.push_back(i);
}
// Now suppose that I want to erase the last three elements
int nEraseCount = 0;
for (std::vector<int... | You can convert from reverse_iterators to iterators using base() although you need to subtract one to get the one that points to the same element thus rbegin() points to end() and rend() points to begin() (because it is not possible to point to one before the beginning in reality).
You have more of a problem because yo... |
4,625,362 | 4,625,489 | How Can I Check if a string represents an positive, non-zero int? | I don't need to know WHAT the int is, I just need to know if it is a positive, non-zero integer representation in Decimal representation, with no leading 0's.
It's going to be called for a large number of records, so I'd like it to be as inexpensive a check as possible.
The expected behaviour is that the system should ... | Whilst you could actually go through the process of actually converting it to an int, my assumption is that what you really want to know is whether all the characters in it are digits?
Unfortunately even then there is no option but do linearly run through the string, although this should be faster than converting to an... |
4,625,549 | 5,168,719 | Using stl_tree.h on Android NDK results in "No such file or directory" | I'm porting a native library to a NDK application.
When I try to use the stl_tree.h #include, I got the following error.
error: stl_tree.h: No such file or directory
This is my Android.mk file.
LOCAL_PATH := $(call my-dir)
MY_PATH := $(LOCAL_PATH)
include $(call all-subdir-makefiles)
LOCAL_PATH := $(MY_PATH)
include $... | I solved it using the stlport from NDK 5.
|
4,625,745 | 4,625,830 | Stringify and Unstringify template arguments | suppose I have a lot of classes with their "*Pack" counterparts in naming. For example, if I have a class Moo, I have MooPack, if I have Foo, I also have FooPack.
I want to have a c++ templated function which returns a FooPack from a Foo
template <class X, class XPack>
XPack packify(X input){
...
}
Is it possible t... | You don't have to specify Moo, just MooPack, because moo will deduce the argument for you. However, I'd suggest that you make MooPack a typedef or nested class (called Pack) inside Moo itself, in which case you can easily access it by typename X::Pack inside the template.
class Moo {
public:
class Pack {
..... |
4,625,753 | 4,625,865 | How to pass a Function pointer without exposing class details | I'm creating a library that needs to allow the user to set a callback function.
The interface of this library is as below:
// Viewer Class Interface Exposed to user
/////////////////////////////
#include "dataType_1.h"
#include "dataType_2.h"
class Viewer
{
void SetCallbackFuntion( dataType_1* (Func) (dataType_2*... | If you don't want or can't use boost, the typical pattern around callback functions like this is that you can pass a "user data" value (mostly declared as void*) when registering the callback. This value is then passed to the callback function.
The usage then looks like this:
dataType_1* aFunction( dataType_2* a, void*... |
4,626,122 | 4,626,142 | java referencing objects in an array | Is there a similar function to indexof() that will search a string array (preferably unsorted) for a string and return it's index? (or maybe ordinate value?)
for example i am trying:
String[] colours= {"Red", "Orange", "Yellow"};
System.out.println("indexOf(Red) = " +
colours.indexOf("Red"));
...but having no... | String[] colours= {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};
Arrays.asList(colours).indexOf("Red"); // 0
OR
if order doesn't matter then
Arrays.sort(colours);
Arrays.binarySearch(colours,"Red");//binary search takes sorted[natural order] array as input
List
Arrays
|
4,626,223 | 4,626,277 | Strange problem MFC c++ | I am making an simple application in MFC /c++.This code is to ceate a dialog in CWinApp class.It compile fine and also run fine but only if i run it from VStudio.But if i run it directly,runtime error occured and program crashed.
CMyDialog dlg;
m_pMainWnd = (CWnd*)&dlg;
dlg.DoModal();
but if i used the code just below... | In the first case the object is being destroyed (when dlg goes out of scope) but is still pointed to by m_pMainWnd. It's possible/likely that something is causing m_pMainWnd to be used and accessing an object which no longer exists.
Change the first example to:
CMyDialog dlg;
m_pMainWnd = (CWnd*)&dlg;
dlg.DoModal();
m_... |
4,626,375 | 4,626,414 | Why use do { ... } while (FALSE); in C++ outside of macros |
Possible Duplicate:
Are do-while-false loops common?
Is there a reason to have code like:
do {
// a lot of code that only needs to be run once
} while (FALSE);
when the code isn't defining a macro? I know it's a trick when it comes to macros, but is there a reason for it in normal code?
| Well, it does allow you to use the break; (or continue) keyword for early exit if you have a need for that for some reason. That would be kinda ugly though. I'd really rather see it moved into its own routine, with the early exit implemented via a return; statement.
|
4,626,426 | 4,626,536 | Clearing boost::array | I'm using a boost array as buffer for the content I get from the async_read of the boost::asio.
After reading I want to clear/reset the buffer for the next read. Please tell me how can i do this.
| You do not need to clean each reading, just use the amount of bytes read
buffer(array, bytes_readed)
In case you still want, you can use the assign method
array.assign(0);
|
4,626,597 | 4,626,755 | What might you use a nameless struct or union for? | I can see how
union {
uint32_t ip_address
struct {
uint8_t oct1;
uint8_t oct2;
uint8_t oct3;
uint8_t oct4;
};
};
Might be of some use to someone, but struct in a struct example here:
Detail of MS warning C4201 seems a bit odd. Can anyone demonstrate a good usage case?... | A nameless union inside a struct makes sense because it allows you to refer to the members of the union without specifying its name, hence shorter code:
struct {
int a;
union {
int b, c, d;
};
} foo;
So accessing the members of the union is just like accessing a member of the containing struct: foo.a and fo... |
4,626,738 | 4,627,310 | When a constructor is called explicitly is the initializer and member variables constructed? | In the use of "placement new" it is suggested to call the constructor and destructor explicitly.
In this case will the objects initialized in the initializer section of a class also get properly constructed?
Same too with explicitly calling the destructor? Do the member objects get destroyed properly?
|
In the use of "placement new" it is suggested to call the constructor and destructor explicitly.
I don't think so. It will say that you need to call the destructor explicitly.
In this case will the objects initialized in the initializer section of a class also get properly constructed?
Apart from the supplying of t... |
4,626,815 | 4,626,827 | Why is a boolean 1 byte and not 1 bit of size? | In C++,
Why is a boolean 1 byte and not 1 bit of size?
Why aren't there types like a 4-bit or 2-bit integers?
I'm missing out the above things when writing an emulator for a CPU
| Because the CPU can't address anything smaller than a byte.
|
4,626,877 | 4,626,909 | Performing depth-first algorithm from a specific vertex | I am trying to find a way to perform the depth-first algorithm from a specific vertex by using the boost graph library.
The depth-first algorithm provided by Boost library evaluates the graph beginning from the start vertex to the last vertex. But what if the graph has to be searched from a specific vertex?
Any suggest... | Have a look at BGL's documentation.
There is an overload where you can provide the start vertex.
template <class Graph, class DFSVisitor, class ColorMap>
void depth_first_search(const Graph& g, DFSVisitor vis, ColorMap color,
typename graph_traits<Graph>::vertex_descriptor start)
|
4,626,940 | 4,627,030 | Classes and Member Variables | Let's say I have a container class called myList. This container class has a private member variable called capacity that holds the number of values in the instance.
It might be beneficial for users of the class to have access to capacity for, say, knowing when they've reached the end while going through each value in... | Have a capacity getter.
But mark it as a const member:
unsigned int getCapacity() const
{ //^^^^^^^
return capacity;
}
The second solution does not work.
As it is not reliable (one user may update it then the next user would get an invalid value when they read it).
Though you should consid... |
4,626,981 | 4,627,118 | Visual Studio 2010 compiling inline assembly in c++ as if Visual Studio 6? | I have a C++ project created in VS6 that was opened in VS2010 and compiles fine. It contains a class with a bit of inline assembly including the following code:
__asm{
mov eax,this
mov esi,[eax].m_pImage
...
All fine and dandy, until I try and create a new MFC C++ project in VS2010 and add the class with the ass... | The VS6 inline ASM seems like a bug that was fixed. I say that because I am not sure how the compiler could verify that m_pImage was a member of what was loaded in the eax register and therefore could not find the offset. To answer your question, there is no way, I am aware of, to use the old ASM semantics in the VS6 c... |
4,627,242 | 4,627,639 | How does `_setmode` in Visual Studio's CRT interact with `std::wcout`? | According to "Conventional Wisdom is Wrong", the CRT does a fair bit of work in order to smooth out inconsistencies in the handling of Unicode in the console on Win32 if an appropriate flag is set on stdout. However, I'm not using cstdio style functions here -- I'm using the iostreams library. How does _setmode interac... | It doesn't, from memory. There was a question I answered a long time ago now where wprintf() would print correctly but wcout<< wouldn't.
|
4,627,347 | 4,627,517 | Distinguish between single and double click events in Qt | I have a QAbstractItemView that needs to react to single and double click events. The actions are different depending on whether it was single clicked or double clicked. The problem that is occurring is that the single click event is received prior to the double click event.
Is there a recommended way/best practice for... | You can find answer in the thread titled Double Click Capturing on QtCentre forum;
You could have a timer. Start the
timer in the releaseEvent handler and
make sure the timeout is long enough
to handle the double click first.
Then, in the double click event
handler you can stop the timer and
prevent it fro... |
4,627,914 | 4,628,512 | What is the regular expression to find a function containing specific text? | I'm asking this partially because it is something I would find very useful, but also to understand the syntax of the answer so I can make my own, creative, better regular expressions!
So here's the question: I want to find a function in my code and I know part of the function name, and something that is inside of the f... | Pretending that every function has correct indentation (there are no blocks of code that belong to the function and have indentation that is less or equal to indentation of function definition):
/\v(^\s*)regexForFunctionName\(.*[^;](\n\1\{)?(\n$|\n\1\s.*){-}\n\1\s.*\zs(whatToFind)/
(braces around whatToFind are here o... |
4,628,721 | 4,628,801 | Is the c++ mutable keyword bad for threads? | From my understanding of the mutable keyword, one of its primary uses is caching data and computing them when needed. Since they can change (even though they are const) wouldnt it be unsafe or pointless to use them? The caching part modifies the data so there would need to be a lock and from my understanding when you w... |
So is it pointless or bad to use C++'s mutable keyword?
No; the mutable keyword is A Good Thing. mutable can be used to separate the observable state of an object from the internal contents of the object.
With the "cached data" example that you describe (a very common use of mutable), it allows the class to perfor... |
4,628,922 | 4,629,086 | building jsoncpp (Linux) - an instruction for us mere mortals? | I am trying to build jsoncpp on Ubuntu 10.x - however the 'instructions' are at times vague. For example, it is not clear exactly which folder the scons.py file needs to reside in before the lib can be built.
Can someone outline the steps required to build the jsoncpp library? on Linux, or failing that, if anyone is aw... | Here's what I did:
apt-get install scons
wget "http://downloads.sourceforge.net/project/jsoncpp/jsoncpp/0.5.0/jsoncpp-src-0.5.0.tar.gz?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fjsoncpp%2F&ts=1294425421&use_mirror=freefr"
tar -xvzf jsoncpp-src-0.5.0.tar.gz
cd jsoncpp-src-0.5.0
scons platform=linux-gcc
jsoncpp doesn'... |
4,628,946 | 5,470,192 | Loading a Qt app in same process as non-Qt app breaks non-Qt app's tooltips | I have a Qt application wrapped up inside a DLL for plugging into 3rd party applications. When those 3rd party applications start the Qt application, the toolbar tooltips in the 3rd party applications stop working. As soon as I close the Qt application, they work again.
I recreated the problem in Visual Studio by creat... | For what it's worth, I ended up having to put the Qt DLL on its own separate event loop. The Qt DLL has a small API that the host application can call to transfer data across, and I just switched threads on entry so that only the thread that owns the Qt event loop works inside the Qt DLL.
|
4,629,050 | 4,629,196 | Convert an int to ASCII character | I have
int i = 6;
and I want
char c = '6'
by conversion. Any simple way to suggest?
EDIT:
also i need to generate a random number, and convert to a char, then add a '.txt' and access it in an ifstream.
| Straightforward way:
char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char aChar = digits[i];
Safer way:
char aChar = '0' + i;
Generic way:
itoa(i, ...)
Handy way:
sprintf(myString, "%d", i)
C++ way: (taken from Dave18 answer)
std::ostringstream oss;
oss << 6;
Boss way:
Joe, write me an int t... |
4,629,078 | 4,629,390 | expected constructor, destructor, or type conversion before '&' token ERROR | My files:
cpu_add.h
#ifndef CPU_ADD_H
#define CPU_ADD_H
double add_double_double(double a, double b) {return (a+b);}
double add_int_double(int a, double b) {return ((double)(a)+b);}
int add_int_int(int a, int b) {return (a+b);}
#endif
I am allowed only to use the functions above. Can't use the operator '+' in my o... | This is caused because you put all your code in headers (maybe thinking the Java way?).
When you include poly_subtype.h it includes q3.h which then includes poly_subtype.h in an attempt to define various classes. Due to your include guards the second include has no effect. Then when the compiler attempts to compile q3.... |
4,629,121 | 4,629,159 | Xerces-c & shared_ptrs | I'm new to the concept of shared_ptr and was trying to reconstruct my program such that it is using smart pointers instead of the regular ones. I ama trying to use shared_ptr with Xerces-c and I am having trouble initializing my errorhandler.
I have a class that implements the errorHandler.
class Handler: public Error... | If the m_Parser doesn't take a shared_ptr, you can't make it. shared_ptr's aren't a silver bullet, you can only use them in your own code. You can use the .get() method to return the raw pointer under the smart pointer for compatibility with legacy code.
|
4,629,328 | 4,630,360 | I need the boost::mpl implementation of exp() function | Does anybody know where can I find it? Otherwise I'll have to write it by myself.
Thanks.
| There is no exp function in boost::mpl 1.45. I've counted them. Twice.
Perhaps you could create your own by applying the times meta-function recursively.
|
4,629,551 | 4,629,588 | Why won't my code segfault on Windows 7? | This is an unusual question to ask but here goes:
In my code, I accidentally dereference NULL somewhere. But instead of the application crashing with a segfault, it seems to stop execution of the current function and just return control back to the UI. This makes debugging difficult because I would normally like to be ... | Windows has non-portable language extensions (known as "SEH") which allow you to catch page faults and segmentation violations as exceptions.
There are parts of the OS libraries (particularly inside the OS code that processes some window messages, if I remember correctly) which have a __try block and will make your cod... |
4,629,575 | 4,632,145 | Creating C++ client app for some abstract windows server - how to manage TCP connection to server speed? | So we have some server with some address port and ip. we are developing that server so we can implement on it what ever we need for help. What are standard/best practices for data transfer speed management between C++ windows client app and server (C++)?
My main point is in how to get how much data can be uploaded/down... | I found what I wanted. "thrulay, network capacity tester" A C++ code library for Available bandwidth tracking in real time on clients. And there is "Spruce" and it is also oss. It is made using some of linux code but I use Boost library so it will be easy to rewrite.
Offtop: I want to report that there is some group o... |
4,629,629 | 4,630,789 | Assign shortcut keys to buttons - Qt C++ | I have created a GUI using Qt Creator. That is by drag and drop the widgets. Now I want to assign shortcut keys for all of the buttons. Can anyone here please let me know how to do that? Thank you in advance.
| Your buttons probably have a slot connected to their clicked() signal.
To add shortcut keys, you simply connect a shortcut key's activated() signal to the same slot.
In your code, #include <QShortcut> and then you will be able to add a shortcut key for a slot like this:
QShortcut *shortcut = new QShortcut(QKeySequence(... |
4,629,712 | 4,629,727 | simple array cause exception | #include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
float x[1000][1000];
return 0;
}
I get " First-chance exception at 0x01341637 in s.exe: 0xC00000FD: Stack overflow." why?
| Your array is simply too large to fit on the stack. You don't have enough stack space for 1000 * 1000 elements.
You'll need to allocate your array on the heap. You can do this using the new keyword, but an easier way is to just use std::vector.
std::vector<std::vector<float> > floats(1000);
for (unsigned i = 0; i !=... |
4,629,866 | 4,629,999 | Copy data from a local pointer for return value | Heres a theoretical question for you assembly experts working in C++. I am often wanting to return a string (char * or wchar *) from a local variable within a function. As you know this cannot be done, as the local variable loses scope. This gets me curious, would it be possible to push the data stored at this location... | I'm not an expert, but I do know that prologue and epilogue code can mess up what you want to do. If you're really doing that (which, needless to say, is bad practice), take a look at naked.
|
4,629,915 | 4,630,038 | rvalue references break when deep-returning | I've encountered a problem when passing returned rvalue references from a depth of more than 1.
struct Data {
std :: vector <int> data;
Data () {
data .push_back (1);
};
Data (Data && d)
: data (std :: move (d .data))
{}
};
Data && foo () {
Data d;
return std :: move (d);
}
Data && bar () {
return std :: ... | You don't return an rvalue reference, you return a value, which is then taken by the caller as by reference as an rvalue. You should just have Data foo(), not Data&& foo(). The fact that any of those works is purely coincidence, as it is undefined behaviour.
|
4,630,752 | 4,630,895 | Equivalent of GtkSpinner in Qt? | I've been searching the Qt docs for something similar to a GtkSpinner, but found only the possibility to use a QProgressBar with minimum and maximum both set to 0, which however is not what I want.
Is there such a widget in Qt?
| QLabel label;
QMovie * movie = new QMovie("animated.gif");
label.setMovie(movie);
movie->start();
As seen in spinner (delay) button thread on QtCentre
|
4,630,805 | 4,630,987 | Removing g++ warning for template parameter | I have a simple class:
template<size_t N, typename T>
class Int
{
bool valid(size_t index) { return index >= N; }
T t;
}
If I define an instance of this class as:
Int<0, Widget> zero;
I get a g++ warning:
warning: comparison is always true due to limited range of data type
I tried to do this, but I couldn't ... | So, I've come up with the following solution:
template<size_t N>
bool GreaterThanOrEqual(size_t index)
{
return index >= N;
}
template<>
bool GreaterThanOrEqual<0l>(size_t index)
{
return true;
}
So now, the class looks like:
template<size_t N, typename T>
class Int
{
bool valid(size_t index) { return Gre... |
4,630,941 | 4,631,334 | Failed to specialize function template | This is homework, although it's already submitted with a different approach.
I'm getting the following from Visual Studio 2008
error C2893: Failed to specialize function template 'void std::sort(_RanIt,_RanIt,_Pr)'
The code is as follows
main.cpp
Database<> db;
db.loadDatabase();
db.sortDatabase(sort_b... | I'm not sure this is what's causing the problem, as it has nothing to do with specializing std::sort, but in sortDatabase you shouldn't be passing in a functor that's meant to behave polymorphically. The reason is that std::sort accepts your function object by value, which means it gets copied as a sort_by object, not ... |
4,630,945 | 4,631,010 | MS Detours Library, detouring non win api function | I want to use the windows detours library to detour a non win api function. The function is part of the Qt library (QtGui4.dll). I am wondering how I would set up the function signature for :
void QPainter::drawText ( const QPointF & position, const QString & text )
I had a go with this and it received my usual shar... | The type of your functions is FnType:
typedef void (QPainter::*FnType)(const QPointF &, const QString &);
but it looks like what they expect is a WINIAPI = __stdcall C function instead. You might think if you can wrap your function into a C function.
|
4,631,038 | 4,631,222 | Trouble with __VA_ARGS__ | C++ preprocessor __VA_ARGS__ number of arguments
The accepted answer there doesn't work for me. I've tried with MSVC++ 10 and g++ 3.4.5.
I also crunched the example down into something smaller and started trying to get some information printed out to me in the error:
template < typename T >
struct print;
#include <bo... | __VA_ARGS__ was originally introduced in C99 and prior to C++11 was not part of the C++ standard. The compiler you’re referencing here doesn’t support C++11 (I believe), though more modern compilers should be able to handle this just fine.
|
4,631,053 | 4,631,083 | Losing strict weak ordering in set | I thought that STL containers set and map provide elements in a strict weak ordering. However, I've found that if I get an iterator through find and change element's value through dereferencing, it doesn't restore order, which violates 23.1.2.2 and 23.3.3.2. Here is the code
int nv = 3;
set<int> s = set<int>();
s.i... | set's iterator and const_iterator are both constant iterators. You are not allowed to modify set's values, only removing and inserting.
|
4,631,164 | 4,631,786 | Boost Unit Test Framework: How to show a per test suite message | Say, I have many test suites attached to the master suite. They run turn by turn. How to print a text message before each suite starts running? If I do it in initialization functions, everything is printed at the very beginning, before any suite starts running. If I do it inside a test function, the message may appear ... | Change the value of log_level:
all - report all log messages including the passed test notification
success - the same as all
test_suite - show test suite messages
message - show user messages
warning -report warnings issued by user
error - report all error conditions
cpp_exception - report uncaught c++ exception
syst... |
4,631,254 | 4,631,294 | How should I test a stand alone application on different OS | I have developed an application with c++ on Vista. It works OK. But Now I want to be sure that it works on XP, on Windows 7, and later may be on some types of linux. What good methods do developers use for this task?
| There is no substitute for actually running it on the platform itself. If you cannot afford to have separate machines dedicated to each platform then you need to:
Partition the disk(s) on a single machine and install each O/S in its own partition, and multi-boot between them.
Use virtualization software like VMWare o... |
4,631,267 | 4,631,409 | different charset for multiple params with dllimport | Is it possible to declare different charset options for seperate params?
heres what i mean:
[dllimport("my.dll", charset = charset.Ansi)]
void myfunc(string CharPtrInCPP, StringBuilder WCharPtrInCPP);
the problem is the c++ function takes a char* for the filename and a wchar* for the data recieved back...
in c++:
void... | As already pointed out, you should be able to specify MarshalAs for each parameter. Another way would be to specify a default character set type and then specify the marshalling for the odd one out. For example,
[DllImport("my.dll", CharSet=CharSet.Unicode)]
void myfunc( [MarshalAs( UnmanagedType.LPStr )] String ... |
4,631,289 | 4,631,328 | Have main thread wait for a boost thread complete a task (but not finish) | I have found plenty on making one thread wait for another to finish executing before continuing, but that is not what I wanted to do. I am not very familiar with using any multi-threading apis but right now I'm trying to learn boost. My situation is that I am using my main thread (the starting one from int main()) to... | If you want to wait for the thread to finish simply use join() (http://www.boost.org/doc/libs/1_45_0/doc/html/thread/thread_management.html#thread.thread_management.thread.join)
If you are waiting for a signal a simple solution is to use a mutex. The barrier mutex of boost should work for you:
http://www.boost.org/doc/... |
4,631,292 | 4,631,379 | How to detect the current screen resolution? | How do I from Winapi (in C or C++) detect the current screen resolution?
Some background:
I want to start a new OpenGL fullscreen window, but want it open with the same horizontal and vertical size which the desktop already is set to. (Now when everyone uses LCD screens, I figured this is the best way to get the native... |
Size of the primary monitor: GetSystemMetrics SM_CXSCREEN / SM_CYSCREEN (GetDeviceCaps can also be used)
Size of all monitors (combined): GetSystemMetrics SM_CX/YVIRTUALSCREEN
Size of work area (screen excluding taskbar and other docked bars) on primary monitor: SystemParametersInfo SPI_GETWORKAREA
Size of a specific ... |
4,631,314 | 4,631,353 | Should constant constructor aguments be passed by reference or value? | When const values are passed to an object's constructor should they be passed by reference or value?
All textbook examples of constructors and initializers pass by value, but this seems inefficient to me.
If you pass by value and the arguments are immediately used to initialize a member variable, are two copies being... | You are choosing here between passing a reference and passing a value. Note that these function signatures are identical.
Point( int x, int y );
Point( const int x, const int y );
From a callers point of view it doesn't matter whether the parameter is modified or not as a copy is always made when parameters are passe... |
4,631,329 | 4,631,766 | C++ Virtual keyword as a way to avoid including code units | Currently we have a body of code that allows service plugins which offer forms of communication to the core e.g tcp/ip, udp/ip, usb, etc... These service plugins feedback notifier class instances to the core for further processing.
In the current implementation a service project (which is a separate dynamically linked ... | Yes, exposing an interface with pure virtual functions to consumers is the standard way of exposing C++ objects from a Windows DLL. The client isn't aware of any implementation details: no member variables, no member function bodies, just virtual layout.
(Add reference counting and a language-agnostic version of dynam... |
4,631,637 | 4,631,674 | c++ casting base class to derived class mess | If I were to create a base class called base and derived classes called derived_1, derived_2 etc... I use a collection of instances of the base class, then when I retrieved an element and tried to use it I would find that C++ thinks it's type is that of the base class, probably because I retrieved it from a std::vector... | If you store your objects in a std::vector<base> there is simply no way to go back to the derived class. This is because the derived part has been sliced of when storing it in an instance of base class (afterall your vector contains copies of your data, so it happily copies only the base part of your objectes), making ... |
4,632,052 | 4,640,582 | SEGFAULT Getting Results Using MySQL/C++ Connector | I'm trying to display a small MySQL table via C++ using the MySQL/C++ Connector, but when I execute the following function, my program either quits with the message "Aborted" or I get a segfault. Can anyone tell me what I'm doing wrong here? I thought I followed the documentation pretty well. :/
void
addressBook::displ... | The problem was that the libraries were installed incorrectly on my system; according to the docs, you run make clean as an intermediary step, when it should just be make.
Thanks to vinleod from ##c++-basic (Vincent Damewood of http://damewood.us/) for the help in figuring that out.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.