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 |
|---|---|---|---|---|
7,107,330 | 7,107,544 | Proper use of new/delete | As a sequel of my previous question, I would like to ask what I am doing wrong in the following code.
The code is, for example
void myclass1::myfun()
{
myclass2* newVar = new myclass2();
/* other code and stuff */
myvector.push_back(newVar); // myvector is a member of myclass1 and is a std::vector<myclass2*>
delete new... | As already said, you cannot access or change memory when you have freed it already. You must take care of deleting your object in your destructor (or an extra function). Here's a snippet that would do that:
// this function adds the object
`void MyClass1::AddFun()
{
myClass2* Ptr = new myClass2(); // create new obje... |
7,107,334 | 7,107,830 | Adding constructor to third party class/struct definition | A third party library has structs defined as
typedef struct _Example
{
int member;
} Example;
As a side question, just out of interest, why that definition? Why not struct Example { ... }?
Anyhow, I want to serialize the information with boost::serialization, and for that need a constructor. Is it safe to just chang... | Your struct has a constructor. Compiler generated for you a no-arg constructor and thats exactly what boost::serialization needs.
|
7,107,606 | 7,107,783 | Why can't I create an array of automatic variables? | In C++0x (ohh! read C++11), we have automatic type inference. One thing which made me curious was that I can't create an array of auto variables. For example:
auto A[] = {1, 2, 3, 4}; // Error!
Any ideas why this might have been disallowed?
| auto deduces every brace-enclosed initializer list to a std::initializer_list<T>. (See §7.1.6.4.6 including the example).
Unfortunately you cannot initialize an array or even std::array from a std::initializer_list once you have obtained it, but you can use a std::vector.
#include <vector>
#include <array>
#include <in... |
7,107,643 | 7,108,053 | c++ heuristic for estimating function inlining benefits | In c++, what is a good heuristic for estimating the compute time benefits of inlining a function, particularly when the function is called very frequently and accounts for >= 10% of the program's execution time (eg. the evaluation function of a brute force or stochastic optimization process). Even though inlining may b... | There is no general answer. It depends on the hardware, the number and
type of its arguments, and what is done in the function. And how often
it is called, and where. On a Sparc, for example, arguments (and the
return value) are passed in registers, and each function gets 16 new
registers: if the function is complex... |
7,107,825 | 7,112,236 | Using Hardware Performance Counters in Linux | I want to use the Hardware Performance Counters that come with the Intel and AMD x86_64 multicore processors to calculate the number of retired stores by a program. I want each thread to calculate its retired stores separately. Can it be done? And if so, how in C/C++?
| You can use Perfctr or PAPI if you want to count hardware events on some part of the program internally (without starting any 3rd party tool).
Perfctr quickstart: http://www.ale.csce.kyushu-u.ac.jp/~satoshi/how_to_use_perfctr.htm
PAPI homepage: http://icl.cs.utk.edu/papi/
PerfSuite good doc: http://perfsuite.ncsa.illin... |
7,107,832 | 7,108,147 | Increases physical memory continuously Visual C++ CryptMsgClose and CryptReleaseContext | I am using C++ and Visual Studio 2005.
I have a project that memory Increases in a very abnormal. When debug the code I Realized That there are Several parts That Contribute to it. Like this for example:
// has to add crypt32.lib to link
#include <windows.h>
#define MY_ENCODING_TYPE (PKCS_7_ASN_ENCODING | X509_ASN_EN... | You have to release resources in reverse order of their acquisition:
CryptAcquireContext();
if (success)
{
CryptMsgOpenToDecode();
if (success)
{
CryptMsgClose();
}
// else: nothing to close, opening failed
CryptReleaseContext();
}
// else: nothing to release, acquisition failed
The dee... |
7,107,884 | 7,108,323 | Why are all references to my IDispatch object not released? | I'm hosting an IWebBrowser2 control in my C++ program using nothing but plain Win32 (no mfc, atl, wtl etc). On DISPID_NAVIGATECOMPLETE2 I add a custom object to be accessed from javascript running on the displayed webpage.
To add the custom object I call InvokeEx with DISPATCH_PROPERTYPUT and a DISPPARAMS structure wit... | Well, you are assigning a property, aren't you? As long as this property exists and refers to your object, it will have a reference added.
If you want the remote object to release your reference you should assign NULL to the property, or some other object.
|
7,108,033 | 7,108,123 | Template Specialization VS Function Overloading | A textbook I have notes that you can provide your own implementation for standard library functions like swap(x,y) via template specialization or function overloading. This would be useful for any types which can benefit from something other than an assignment swap, like STL containers for example (which already have ... | Short story: overload when you can, specialise when you need to.
Long story: C++ treats specialisation and overloads very differently. This is best explained with an example.
template <typename T> void foo(T);
template <typename T> void foo(T*); // overload of foo(T)
template <> void foo<int>(int*); // specia... |
7,108,059 | 7,150,742 | Convert boost::posix_time::ptime to string using custom time zone | I have a boost::posix_time::ptime instance and would like to convert ("format") it to a string using a given boost::local_time::time_zone_ptr instance. Below is a test program showing what I currently have. It converts a ptime to a local_date_time which, from my understanding, expresses a time zone in addition to the t... | I think boost does not know the time zone specifier. Replace
new boost::local_time::posix_time_zone("EST")
in your code by
new boost::local_time::posix_time_zone("EST-05:00:00")
and everything works fine. If you want to use the common standard names, you have to create a timezone database as described in the boost do... |
7,108,161 | 7,108,232 | Simple variadic template function can't instantinate | I'm aware that sizeof...(Args...) yields the number of types in a C++0x packed template argument list, but I wanted to implement it in terms of other features for demonstation purposes, but it won't compile.
// This is not a solution -- overload ambiguity.
// template <typename... Args> size_t num_args (); // ... | You didn’t declare a base case. You have a template-free overload of your num_args function but when calling a function num_args<T...>() this will never be found, for obvious reasons: it will always try to instantiate a function template.
You can however specialise your function template to perform the desired operatio... |
7,108,174 | 7,109,405 | How do I read the image currently on the framebuffer in Qt/C? | Is there any way I can read the content of the framebuffer in Qt or anyway in C? I read it is possible to write the content of /dev/fb0 to a file and then load it. But is it possible to avoid saving it to memory and simply copy to a new memory location to use in Qt?
Thanks!
| The ordinary Qt distribution is not likely to have special support for reading a framebuffer on Linux. It layers on top of X11 and is trying to provide cross-platform capability (as things like /dev/fb0 won't have meaning on Windows, for instance). So you would use higher level abstractions, such as the QPixmap::grab... |
7,108,349 | 7,109,677 | Modify a document with TinyXML | Right now, I save my data by simply rewriting the file requested by the user. The way my xml is structured is like this:
Skeleons root
Skeleton with string name attribute
bone with attributes
bone with attributes
bone with attributes
bone with attributes
end Skeleton
Skeleton with... | Basically, this is just a matter of splitting the steps.
First, define a TiXmlElement * and set it to 0. Iterate over all children of Skeletons. If you find the correct Skeleton, point your TiXmlElement * to it.
Secondly, if you haven't found it (TiXmlElement * still 0), create a new Skeleton and point your TiXmlElemen... |
7,108,425 | 7,108,520 | Why is the size not a template argument of std::initializer_list? | std::initializer_list is constructed by the compiler from a brace-enclosed init list and the size of this list must be a compile time constant.
So why did the committee decide to omit the size from the template arguments? This possibly prevents some optimizations and makes some things impossible (initializing std::arr... | One upside of the existing system is that you can export functions which take an initializer_list from a DLL. If it were templated on the size, they would have to be shipped as source.
|
7,108,649 | 7,108,833 | c++, pointers, references, passing from one to another function, std::vector, std::string | i have a specific problem with pointers and references, with std::vector and std::string. Some question are in the following code snipped, some below.
I have basically this code
//first of all: is this function declaration good?
//or shoudl I already pass the std::vector in another way?
//I'm only reading from it
void ... | That is a good declaration, as long as the function is not intended to modify the vector. It's more efficient than passing by value, since it avoids copying the vector - an expensive operation requiring a memory allocation.
However, the other function requires a non-const pointer. How to handle this depends on whether ... |
7,108,691 | 7,109,570 | What is the best data structure for a generic step function? | I need to implement a step function (i.e. piecewise constant). There are a few requirements that it will need to have.
It will have to be evaluated repeatedly at random locations, then evaluated sequentially over an interval.
It Will have to be easily updated, i.e. adding an increase/decrease over an interval.
So ... | Yes, since the intervals cannot overlap, binary tree is the right data structure. If you did not need fast updates, it could be as simple as having a sorted sequence of the interval endpoints; querying the function value at a certain location could be done using, for example, one of the STL binary search methods std::l... |
7,108,725 | 7,108,830 | How to avoid repeated SendMessage | I have a problem: I use SendMessage from a procedure in a DLL to communicate with the main window; procedure is a hook procedure that allows main window to know when mouse right button is clicked in a editbox; it sends also handle of the editbox. It works well, except for this bug: when program is running without break... | It is probably because you are sending the message for WM_RBUTTONDOWN and WM_RBUTTONUP, that is when the right button is pressed and when it is released.
When you are debugging the WM_RBUTTONUP is eaten by the debugger so you don't get it.
PS: Shouldn't you use PostMessage() instead of SendMessage(), just to be safe?
|
7,108,740 | 7,108,793 | Why simple mysql++ code compiles standalone, but not in project? | At first, small program:
#include <mysql++.h>
using namespace mysqlpp;
void mainuu ()
{ Connection conn("mysql", "localhost", "root", "pwd");}
If I compile it as one file in CodeLite or in such way:
g++ -I/usr/include/mysql -I/usr/include/mysql++ -lmysqlclient -lmysqlpp -o Test mysql_api.cpp
it's ok
but, when I try ... | Looks like you need to edit CodeLite project settings and add these settings -lmysqlclient -lmysqlpp that you pass in command line. Fill Library Path and Libraries fields on Linker tab.
|
7,108,797 | 7,108,879 | Can I selectively (force) inline a function? | In the book Clean Code (and a couple of others I have come across and read) it is suggested to keep the functions small and break them up if they become large. It also suggests that functions should do one thing and one thing only.
In Optimizing software in C++ Agner Fog states that he does not like the rule of breakin... | You cannot force the inline. Also, function calls are pretty cheap on modern CPUs, compared to the cost of the work done. If your functions are large enough to need to be broken down, the additional time taken to do the call will be essentially nothing.
Failing that, you could ... try ... to use a macro.
|
7,108,902 | 7,660,742 | Standard layout and inheritance | What is the reason that the second class is not standard layout? (Visual Studio C++)
#include <iostream>
#include <type_traits>
struct A
{
int i;
};
struct B : public A
{
};
std::cout << "is_standard_layout<B> == "
<< std::boolalpha
<< std::is_standard_layout<B>::value // gives false
... | Accorting to this MSVC supports built-in type traits since version 8 but this seems to say that you need version 11.
Section 9.7 defines a standard-layout class as a class that:
has no non-static data members of type non-standard-layout class (or array of such types) or reference,
has no virtual functions (10.3) and ... |
7,108,914 | 7,109,126 | What should happen to template class static member variables with definition in the .h file | If a template class definition contains a static member variable that depends on the template type, I'm unsure of what the reliable behavior should be?
In my case it is desirable to place the definition of that static member in the same .h file as the class definition, since
I want the class to be general for many tem... | From N3290, 14.6:
A [...] static data member of a class template shall be defined in
every translation unit in which it is implicitly instantiated [...], unless the corresponding specialization is explicitly instantiated [...] .
Typically, you put the static member definition in the header file, along with the temp... |
7,108,998 | 7,109,064 | c++ linking error when doing __inline__ on class member function: symbol not found | I'm trying to force inline a member function and I get the error:
"a_class::mem_func()", referenced from:
func(a_class&) in func.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
here is the distilled error-producing code
a_class.h
#ifndef A_CLASS_H #define A_CLASS_H
class a_class {public: __in... | If you want to make sure your function is inlined, move the definition in the header:
a_class.h
#ifndef A_CLASS_H #define A_CLASS_H
class a_class {public: __inline__ void mem_func() {} /*<-definition*/; };
#endif
|
7,109,007 | 7,109,330 | What options are available for c++ memory debugging in OpenBSD? | I believe I have a double delete and some memory corruption happening somehow in my complex c++ application on OpenBSD. I would like to track down the first location my object is deleted, and any points at which deallocated memory is accessed.
I would usually look into valgrind, but it is linux only. Failing that, I ... | This helps a lot:
man malloc
Debugging options can be enabled system-wide, environment-wide, or program-specific.
|
7,109,420 | 7,110,361 | Why is this variadic function ambiguous? | This is related to my earlier post. I'd like to know why one attempted solution didn't work.
template <typename... T> /* A */
size_t num_args ();
template <>
size_t num_args <> ()
{
return 0;
}
template <typename H, typename... T> /* B */
size_t num_args ()
{
return 1 + num_args <T...> ();
}
If I... |
I don't understand how this is ambiguous -- A is a declaration and B
is a definition of the function declared by A. Right?
No. A is a declaration of a function template, and B is a declaration (and definition) of another function template.
The compiler has no way to decide between the two: they both have no argumen... |
7,109,451 | 7,109,563 | Do all STL containers return their elements by reference? | I am learning STL these days and I was wondering if STL containers return by reference?
e.g:
vector.first();
map[key];
*vector.begin();
Or any possible return that ends with element (or value type) of container
e.g:
std::vector<int> elements;
elements.push_back(20);
elements[0]=60; // this will also change the value
e... | Returning the added element, or the container in container member functions is not possible in a safe way. STL containers mostly provide the "strong guarantee". Returning the manipulated element or the container would make it impossible to provide the strong guarantee (it would only provide the "basic guarantee"). An e... |
7,109,566 | 7,109,938 | Should virtual dispatch happen when a virtual method is called within a virtual method using object? | struct B
{
virtual void bar () {}
virtual void foo () { bar(); }
};
struct D : B
{
virtual void bar () {}
virtual void foo () {}
};
Now we call foo() using an object of B as,
B obj;
obj.foo(); // calls B::bar()
Question:
Should bar() will be resolved through virtual dispatch or it will be resolved using the... | Entirely up to the implementation. Nominally it's a virtual call, but you're not entitled to assume that the emitted code will actually perform an indirection through a vtable or similar.
If foo() is called on some arbitrary B*, then of course the code emitted for foo() needs to make a virtual call to bar(), since the ... |
7,109,670 | 7,109,815 | Determining address memory of a library | I'd like to know if somebody would know some tools which can tell you the address memory for a static or dynamic library written in C++ (for windows, linux and macos).
Thanks
| You can use readelf for Linux, which displays information about ELF files. You can use it to know the addresses of shared libraries (implicitly loaded dynamic libraries) as well as addresses of all the static symbols. You can't however use it for libraries which are explicitly loaded at runtime. You can turn off the Ad... |
7,109,684 | 7,109,780 | std::auto_ptr<T> Usage | I've read a reasonable amount in decent textbooks about the auto_ptr class. While I understand what it is, and how it gets you around the problem of getting exceptions in places like constructors, I am having trouble figuring out when someone would actually use it.
An auto_ptr can only hold a single type (no array new... | I'll give you a short example for a good usage. Consider this:
auto_ptr<SomeResource> some_function() {
auto_ptr<SomeResource> my_ptr = get_the_resource();
function_that_throws_an_exception();
return my_ptr;
}
The function that raises an exception would normally cause your pointer to be lost, and the obj... |
7,109,781 | 7,113,383 | Input Data in my Combo Box | I feel really silly asking this question but how do you add any data to a Combo Box? Like I want to display A,B and C as my dropbox strings but I have tried out many things, still my Combo Box does not display anything.
I have tried setting the 'Data' property with A;B;C..still it doesn't show this.
I tried this in m... | Make sure your combobox has a height that can hold all entries. The height of a combo box doesn't affect the combo box itself, but the dropdown list.
You can change it in the dialog editor:
Click on the down arrow of the combo box, now there should be a rectangle that allows you to change the height of the combobox dro... |
7,109,795 | 7,109,829 | Macro definition conflict | I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.
I have two header files
test1.h
#define TEST 123
test2.h
#define TEST 456
Now I have a program included both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?
You m... | You can use the #ifdef pre-processor directive to determine if TEST is defined already for your particular case. Or just #undef it first.
#undef TEST
#define TEST 123
Put that in your header file where you want TEST to be 123 and not 456. Also, this needs to be before test1.h.
|
7,110,105 | 7,110,167 | Template function for max_element on maps needs to know both types | I'm trying to write a custom cmp function for a map, a simple one that does the comparison over the second element of the map. I'd like to have the function as a template, but I can't figure out how to pass the map's .first and .second types along to my cmp function. My non-working code is below, which will clearly fai... | std::map has a nested type called value_type which is actually a typedef of std::pair<const K, V>. And std::pair has two nested types first_type and second_type. Use this info as:
template<class T>
typename T::const_iterator map_max_element(const T & A)
{
typedef typename T::value_type pair_type;
typedef typena... |
7,110,379 | 7,110,432 | A portable boost.xpressive | I want to use Boost.Xpressive in my C++ homework, and contain it in my source. But the whole boost header file is 70MB+, so is there any standalone xpressive distribution that contains only dependent files?
| Use bcp. http://www.boost.org/tools/bcp/index.html.
it allows you to pull a header and all of its dependencies into a separate directory. Which will be much smaller than the whole boost library!
I don't know specifically, but the command line you are looking for is probably something like this:
bcp xpressive /foo
|
7,110,560 | 7,111,380 | Whats wrong with my code to attach and use console from another process? | I have server process, its allocate console and redirect output and input to that console. With ShellExecute this server process spawn some clients, these client know server ProcessID. So, i try AttachConsole with next class:
Console::Console(DWORD dwProcessId)
{
if (dwProcessId) {
AttachConsole(dwProcessI... | You should open CONOUT$ using CreateFile. Attaching to a console does not change the starndard handles that your process has inherited.
|
7,110,672 | 7,110,852 | Does "new char[]" need to be release resources manually? | For this:
m_sFilename = new char [len+1];
Should I call delete[] m_sFilename; sometime?
And:
should I use delete[] m_sFilename or delete m_sFilename;?
|
Does "new char[]" need to be release resouces manually?
Yes.
For this: m_sFilename = new char [len+1];
Should I call delete[] m_sFilename; sometime?
Yes.
Should I use delete[] m_sFilename or delete m_sFilename;?
delete[].
But you should actually use std::string, which does all this for you, and is free.
|
7,110,709 | 7,111,022 | Concurrent Queue using Qt is deadlocking | I am trying to create a concurrent queue with Qt's concurrent threading constructs.
#ifndef CONCURRENTQUEUE_H
#define CONCURRENTQUEUE_H
#include <QMutex>
#include <QWaitCondition>
#include <queue>
template<typename Data>
class ConcurrentQueue
{
private:
std::queue<Data> the_queue;
QMutex the_mutex;
QWaitCo... | You forgot to add
the_condition_variable.wakeOne();
in try_pop.
If there will be multiple producers / consumers accessing your queue, you should have a separate QWaitCondition for producers and consumers, otherwise wakeOne might not wake the correct thread.
EDIT:
If there will be multiple producers / consumers, then y... |
7,110,941 | 7,111,186 | How to disable std::cerr? | I got a program which contains a lot of std::cerr, it directly outputs to my terminal. I am wondering what is the difference between std::cerr and std::cout. And how can I disable the std::cerr (I don't want it output to my screen)?
| As others have mentioned, if this is a Unix-like system then 2>/dev/null redirects stderr (2) to the big bit bucket in the sky (/dev/null).
But nobody here has explained what the difference between stderr and stdout is, so I feel obligated to at least touch on the topic.
std::cout is the standard output stream. This is... |
7,110,945 | 7,110,980 | Does a function local static variable prevent function inlining? | I'm writing an attribute shim to get the raw c-string from a library's string implementation. This specific string class, say string_t has members length() and data().
When length() == 0 data() == nullptr.
Now I am using an api that doesn't like null strings so my shim returns the address of an empty string.
inline c... | No, it does not prevent inlining. There will still be only one instance of the function-local static variable, and everywhere the function is expanded inline, that instance will be used.
Whether a particular compiler with particular options actually inlines such a function is another matter, and you'd have to compile ... |
7,110,959 | 7,110,985 | Delete char array. Alternative way? |
Possible Duplicate:
Is it necessary to call delete[] vs delete for char arrays?
char *p = new char[200];
delete p;
This kind of (I changed var name) code is from a big commercial project.
The third line. Is this right?
Should I change it or leave it there. Coz no bug report for this and this programs runs more tha... | You have to use delete[] since you used new[], it's not an alternative.
delete [] p;
|
7,111,041 | 7,159,491 | boost serialization multiple objects | Slightly related question to this one and this one.
Basically, I would like to serialize objects as they come, much like a log file, except that I want to unserialize them later. This means that I don't have all the objects initially.
From previous answers, it looks like if one keeps the same archive open, one can keep... | Here is what I did in the end. Since Nicol is right and this really is a bit of not-intended use, first one has to make sure to disable pointer tracking. Otherwise one gets spurious shared objects. Hence to begin with, loads of
BOOST_CLASS_TRACKING(yourDerivedClass,boost::serialization::track_never)
I also settled fo... |
7,111,089 | 7,119,089 | What's the essential difference between these two variadic functions? | I've been frustrated by a simple variadic template function:
constexpr size_t num_args () {
return 0;
}
template <typename H, typename... T>
constexpr size_t num_args () {
return 1 + num_args <T...> ();
}
int main () {
std :: cout << num_args <int, int, int> ();
}
The above doesn't compile, see above lin... | I'm starting to think that the difference is that
foo (args...);
exploits overloading whereas
num_args <T...> ();
exploits specialisation.
Overloading can handle the base case but specialisation can't for function templates (but it can for classes) which is why auxilliary_class<Args...>::value is idiomatic.
|
7,111,251 | 7,111,275 | pass function by value (?) instead of function pointer? | Sorry if this has been asked before, but I was unable to find it.
So im trying to educate myself about templates and the new C++11 features (mainly lambdas, something I always liked in other languages).
But in my tests I came to something I had no idea it worked, and I'm trying to understand how it works but cant figur... | A function is implicitly convertible to a pointer to itself; this conversion happens pretty much everywhere. Test(Callback) is exactly the same as Test(&Callback). There is no difference. In both cases, Func is deduced to be void(*)(int).
Function pointers are weird. You can find out more about them in "Why do al... |
7,111,252 | 7,111,301 | forward declaration of class using templates | Can I use forward declaration for template class?
I try:
template<class que_type>
class que;
int main(){
que<int> mydeque;
return 0;
}
template<class que_type>
class que {};
I get:
error: aggregate 'que<int> mydeque' has incomplete type and cannot be defined.
| Forward declaration of a class should have complete arguments list specified. This would enable the compiler to know it's type.
When a type is forward declared, all the compiler knows about the type is that it exists; it knows nothing about its size, members, or methods and hence it is called an Incomplete type. Theref... |
7,111,311 | 7,111,637 | C++: _beginthreadex, thread function name not showing in Visual Studio Threads window | I recently learnt that ::_beginthreadex() is always preferable to ::CreateThread(), so I changed all my calls that used ::CreateThread().
The only downside is that I no longer see the thread function's name in Visual Studio's Threads window making it hard to quickly identify threads. I assume this was somehow done auto... | This happens because _beginthreadex() calls CreateThread() with its own thread function that calls the one you specify (so the debugger uses the _threadstartex function name - the one that _beginthreadex() invokes).
You can manually set the thread name yourself using the SetThreadName() example from MSDN. What you mig... |
7,111,386 | 7,112,020 | Trying to do serial port communications, getting back 0x102 as a return code | I'm working on a program in C# which communicates with a piece of hardware over the serial port (said serial port communication being handled by a C++ library). It is meant to replace an earlier piece of software which has become unmaintainable. Currently, it is not working at all how I desire it to. On my work laptop,... | MS says that 0x102 is an NTSTATUS meaning
The given Timeout interval expired.
http://www.stallion.com.au/html/userdoc/easyadmw/easyadmw_2.html says something similar
Last Status This is the NT_STATUS code of the last Read IRP
(IRP_MJ_READ) completed by the driver. The actual code can be decoded
from the NT D... |
7,111,442 | 7,111,461 | error: no matching function for call to | I am getting this error:
main.cpp:31: error: no matching function for call to 'QWebFrame::addToJavaScriptWindowObject(QString, Eh*&)'
candidates are: void QWebFrame::addToJavaScriptWindowObject(const QString&, QObject*)
This is the source code:
#include <string>
#include <QtGui/QApplication>
#include <QWebFrame>
#incl... | addToJavaScriptWindowObject takes a QObject* as its second parameter. So you need to have Eh inherit from QObject.
Try something like this:
class Eh : public QObject {
Q_OBJECT
public:
Eh(QObject *parent = 0) : QObject(parent) {
}
int lol() {
return 666;
}
};
|
7,111,549 | 7,111,607 | Creating a serial number | I'm trying to create a serial number for my program.
I'd like it to represent the relevant dates as well as the user's name, company's name, etc.
Is there a common way to do this?
A link to a tutorial/ article will be greatly appreciated.
| You can have a look to the definition of the UUID (Universal Unique ID) which allows you to generate a unique number based on different parameters (MAC, date...)
|
7,111,753 | 11,122,236 | SendMessage() WINAPI gets hang when used to connect to a DDE server | I have a DDE client app which connects to the DDE server app by using SendMessage() WINAPI. Following the SendMessage() call which gets hang while requesting connection to the DDE Server. Both DDE Client app and server app are in VC++.
SendMessage((HWND) -1,WM_DDE_INITIATE,(WPARAM) m_hWnd,MAKELPARAM(hService,hTopic));
... | Use SendMessageTimeout instead of SendMessage so the hung apps will not hang you.
|
7,111,843 | 7,112,815 | Why the Compiler does not detect correct function signature in error? | The question is in reference to this, which was posted a little while earlier.
While the OP was happy accepting the answer which solved his problem I was a little intrigued with a detail as to why compiler gave a seemingly wrong error.
Below is a small code sample I created to demonstrate the same:
class YourClas... | As others have stated, the compiler is trying to be helpful, and probably confusing you. Lets start with the simplest error:
error: no matching function for call to obj.doSomething(ptr)
While the error message is correct, the information that it provides is very limited. In this example the code is simple to follow, ... |
7,111,943 | 7,115,320 | Output QVector3D to QString | I was surprised to learn that QVector3D does not have a built-in way of outputting the x, y, and z coordinates as a QString. I can write a simple function to do this, but I was wondering if there was a standard method of doing it?
| You can use QDebug::QDebug(QString*) and the operator << from QDebug :
QString str;
QDebug(&str) << QVector3D(1,2,3);
But because that constructor is not declared explicit, you can omit the QDebug:
QString str;
&str << QVector3D(1,2,3);
(I don't know if this is a bug or a feature, and if you can rely on that second f... |
7,111,957 | 7,112,168 | Is qualified name in the member function declaration allowed? | This code is accepted by MSVC9.0. My question is whether it is legal according to the standard (the old and/or the new one). A quote would be very much welcome, too.
class X
{
void X::f();
};
| No, this is not valid. Here, X::f is a qualified name; you are attempting to use it as a declarator-id. C++03 8.3[dcl.meaning]/1 lists the circumstances under which a declarator-id may be qualified:
A declarator-id shall not be qualified except for
the definition of a member function or static data member outside
... |
7,111,958 | 7,111,987 | knowing which adapter is used to make a socket connection | I have a Visual Studio 2008 C++ application where I connect to a remote TCP server using a socket. The code looks basically like this:
SOCKET s = socket( AF_INET, SOCK_STREAM, 0 );
addrinfo* ai = getaddrinfo( ... );
connect( s, ai->ai_addr, sizeof( sockaddr_in ) );
Assuming my local client has multiple adapters, how c... | You can use getsockname to find out the address.
int getsockname(
__in SOCKET s,
__out struct sockaddr *name,
__inout int *namelen
);
struct sockaddr_in sin;
int sinlen = sizeof(sin);
memset(&sin, 0, sizeof(sin));
getsockname(s, (strict sockaddr *)&sin, &sinlen);
|
7,112,063 | 7,112,115 | Access USB hardware (pressure sensor matrix with native C++ API) using Python | I am working with a pressure-sensing mattress having a USB interface. The maker provides USB device drivers for Windows, and an API written in C++ which has functions to request data and set some parameters.
Currently, I cannot use this sensor for testing some Python data-visualization scripts directly, having had to a... | Odds are fairly good it's a HID device, in which case you can probably start to write a userspace linux driver for it using libhid. First place to start with that would be enumerating the tree that gives you information about its capabilities. (lsusb -vvv or Example)
Failing that you can use libusb on linux (and other ... |
7,112,215 | 7,112,570 | How can I get rid of fixed sentinel value (-32767)? | Below is the program I wrote to find sum of a subarray from given array, however somehow I am not getting how can I get rid of the sentinel value (-32767 in this case)? and how can I optimise it?
and how can I keep track of range of max subarray?
#define EVALUE -32767
using namespace std;
int findMaxSubArray(vector<i... | When reading from a textfile, the last character that cin will get is the "EOF" character, or end of file character. You can send this character to your program in the command line with control+d. You're going to want to check for this rather than -32767.
This is a basic program that should identify a simple fix for yo... |
7,112,282 | 7,112,409 | order of evaluation of operands | In the expression a + b, is a guaranteed to be evaluated before b, or is the order of evaluation unspecified? I think it is the latter, but I struggle to find a definite answer in the standard.
Since I don't know whether C handles this different from C++, or if evaluation order rules were simplified in C++11, I'm gonna... | In C++, for user-defined types a + b is a function call, and the standard says:
§5.2.2.8 - [...] The order of evaluation of function arguments is unspecified. [...]
For normal operators, the standard says:
§5.4 - Except where noted, the order of evaluation of operands of individual operators and subexpressions of... |
7,112,434 | 7,112,476 | c++ code equivalent since c#? | How do you code this code in c++?
public bool returnboolean(bool x)
{ return x; }
public double sum(double one, double two)
{ return one+two; }
public string yourname(string name)
{ return "hello "+yourname; }
Where do i go to write code? in *.h? or in *.cpp?
What is their goals o... | #include <string>
public:
bool returnboolean(bool x)
{
return x;
}
double sum(double one, double two)
{
return one+two;
}
std::string yourname(std::string name)
{
return "hello " + name;
}
|
7,112,675 | 7,112,688 | Creating makefile for a C++ program to run with g++ | I have a sample program in a file called "helloworld.cpp":
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cout<<"Hello World!";
return 0;
}
I am trying to write a makefile for this as follows:
all: g++ helloworld.cpp -o helloworld
Right now I am on windows and couldn't test th... | You have the action to be run on the part of the line where the dependency goes. Try this:
all:
g++ helloworld.cpp -o helloworld
Make sure that's one tab, not spaces in any quantity.
|
7,112,680 | 7,112,795 | partial template specialization | I have a scenario in which there is a template class
template<typename X, typename Y>
class Foo
{
typedef Y::NestedType Bar;
int A (Bar thing);
void B();
int C(X that);
// other stuff
};
and then I would like the A() method to have a different behavior when X is a given type (but B and C can stay the same, and ... | Use overloading
template<typename X, typename Y>
class Foo
{
// allows to wrap up the arguments
template<typename, typename>
struct Types { };
typedef Y::NestedType Bar;
int A (Bar thing) {
return AImpl(thing, Types<X, Y>());
}
void B();
int C(X that);
// other stuff
private:
template<typename X1, typ... |
7,112,698 | 7,112,786 | How can I insert a structure as key into a map? | I'm getting a compiling error for the code below, after removing the comment characters from the first insert line. I'm unable to insert the structure into the map while inserting integers is fine.
# include <iostream>
# include <map>
using namespace std;
struct node
{int test;} temp;
int main()
{
temp.test = 24... | A std::map's keys are stored internally in a binary search tree. In order for keys to be stored and searched for in a binary search tree, they must be comparable. For example, a requirement of a binary search tree is that a left child's key is less than its parent's key and a right child's key is greater than its paren... |
7,112,831 | 7,132,513 | Constructing data pools for components | I'm running Windows 7 with a Core Duo. I've been using Codeblocks for a while now, which I think I have using GNU compiler.
I have (or will have) many component classes that inherit from the abstract class Component. I need help establishing a system to house memory pools for an undetermined amount of component types... | I got wrapped up in how I was implementing this and lost track of what I really needed. Which is basically this post.
Thanks.
|
7,113,099 | 7,125,492 | C++ conversion question | I know that I can use correctly the WinApi function DsGetDcName like this:
DOMAIN_CONTROLLER_INFO* dcInfo = nullptr;
unsigned long res = ::DsGetDcName(nullptr,
nullptr,
nullptr,
nullptr,
0, &dcInfo);
It is unnatural, ... | You would need to look at the assembly. The two options that work (#2 & #3) both use the LEA instruction. This loads the address of the data structure into EAX, which in the case is null. The failing example loads the value of the that address which is null. As you know you cannot dereference null.
// #1 - Fails
::DsGe... |
7,113,396 | 7,113,419 | c++ convert time_t to string and back again | I want to convert a time_t to a string and back again.
I'd like to convert the time to a string using ctime().
I can't seem to find anything on google or the time.h header file, any ideas?
Basically what I'm trying to do is store a date in a file, and then read it back so I can use it as a time_t again.
Also, no li... | You'll have to write your own function to do that. These functions convert any primitive type (or any type which overloads operator<< and/or operator>>) to a string, and viceversa:
template<typename T>
std::string StringUtils::toString(const T &t) {
std::ostringstream oss;
oss << t;
return oss.str();
}
tem... |
7,113,422 | 7,113,474 | Why can it be dangerous to use this POD struct as a base class? | I had this conversation with a colleague, and it turned out to be interesting. Say we have the following POD class
struct A {
void clear() { memset(this, 0, sizeof(A)); }
int age;
char type;
};
clear is intended to clear all members, setting to 0 (byte wise). What could go wrong if we use A as a base class?... | The compiler is likely to add padding bytes to A. So sizeof(A) extends beyond char type (until the end of the padding). However in case of inheritance the compiler might not add the padded bytes. So the call to memset will overwrite part of the subclass.
|
7,113,506 | 7,122,340 | QProcess becomes defunct and unable to start again | I'm using a List of QProcess objects to keep track of some processes that need to be start/stopped at user defined intervals.
I'm able to start and stop the processes OK. But the issue arises when I stop a process using the following methods (Pseudo code):
process->start("PathToProcess","Some Arguments");
//Do some stu... | Figured out what was causing the error.
In qprocess_unix.cpp, you'll find a class called QProcessManager. Essentially this class has signal handlers that watch for child processes that have died. When a child dies, the QProcessManager sends a message across a pipe that lets the QProcess class know that it terminated/... |
7,113,593 | 7,113,821 | Getting numeric timezone in specified format | I would like to print the current time as 2011-08-18 10:11:12 -07:00. I developed a code snippet as below,
#include <iostream>
using namespace std;
void time_to_string(time_t clock,const char *fmtstr )
{
char buf[256];
if (strftime(buf, 256, fmtstr, localtime(&clock)) == 0)
buf[0] = 0;
cout << buf... | You would have to manually split the string which is formated by %z as +hhmm or -hhmm. %z has a fixed format. Look at the description of strftime.
Replaced by the offset from UTC in the ISO 8601:2000 standard format ( +hhmm or -hhmm ), or by no characters if no timezone is determinable.
Build one string with date and... |
7,113,872 | 7,114,071 | inline vs. constexpr? | With the new C++11 standard, when should I use the inline keyword over the constexpr keyword? Does the constexpr keyword offer any additional optimization over inline, or does it merely assert that things must be computed at compile-time?
Why does constexpr work on the GCC in some cases where the call is not constant,... | Asserting that something can be computed at compile-time is a pretty strong kind of optimization.
Inlining merely removes a function call, by copy/pasting the function body into the call site. The function body still has to be executed, you just save the overhead of a function call.
But if you make the same code be eva... |
7,114,026 | 7,114,089 | Pointer math vs. Array index | I know this has been hashed over a number of time, but I have come across a case today that shook my understanding of the pointer math/ array index.
As I have allways understood it, &mybuff[10] and (&mybuff+10) are equivilent ways of referancing the same memory.
However I spent the morning fighting a case where:
mem... | see http://cplusplus.com/doc/tutorial/operators/ for priority order of operators
&mybuff+10 like (&mybuff)+10
&mybuff[10] like &(mybuff[10])
Edit
also some pointers http://cplusplus.com/doc/tutorial/pointers/
|
7,114,043 | 7,114,482 | Random number generation in C++11: how to generate, how does it work? | I recently came across new way to generate random numbers in C++11, but couldn't digest the papers that I read about it (what is that engine, maths term like distribution, "where all integers produced are equally likely").
So can anyone please explain
what are they?
what does they mean?
how to generate?
how do they wo... | The question is way too broad for a complete answer, but let me cherry-pick a couple of interesting points:
Why "equally likely"
Suppose you have a simple random number generator that generate the numbers 0, 1, ..., 10 each with equal probability (think of this as the classic rand()). Now you want a random number in th... |
7,114,140 | 7,114,909 | Deassembling memory function on Windows in C/C++ | I use MSVC 2008.
Let's say I have a function in my code:
int foo()
{
return 2 + 5;
}
What tools can I use to obtain ASCII representation of this routine in X86 assembler?
void bar()
{
std::string s = disassemble(foo);
printf("%s\n", s.c_str());
}
| You can use the marvelous BEAEngine library.
|
7,114,442 | 7,114,666 | sorting vector of vector of strings in C++ | I am having trouble to figure out, how to sort a vector of vector of strings, here is the testing code.
#include <iostream>
#include <vector>
#include <boost/algorithm/string.hpp>
int main(int argc, char** argv) {
std::vector <std::vector <std::string> > data_var;
std::vector <std::string> temp;
s... | If you only want to sort based on the second column, then you just need to provide a custom comparison operator. Once way to do that is:
struct StringListCompare
{
bool operator()(const vector<string>& lhs, const vector<string>& rhs)
{
// what do we do if lhs or rhs don't have two elements?
if (lhs.size() ... |
7,114,465 | 7,114,528 | Is "delete p; p = NULL(nullptr);" an antipattern? | Searching something on SO, I stumbled across this question and one of the comments to the most voted answer (the fifth comment to that most voted answer) suggests that delete p; p = NULL; is an antipattern. I must confess that I happen to use it quite often paring it sometimes\most of the times with the check if (NULL ... | Yes, I would not recommended doing it.
The reason is that the extra setting to null will only help in very limited contexts. If you are in a destructor, the pointer itself will not exist right after the destructor execution, which means that whether it is null or not does not matter.
If the pointer was copied, setting... |
7,114,629 | 7,134,924 | Reading JPEG in ffmpeg | I'm trying to get ffmpeg to encode several individual JPEG images into a video on Android. I've successfully built it for Android (see the configuration string at the end of this post).
I can encode an h.263+ video with randomly generated frame content, and ffmpeg otherwise appears to work well.
A similar question sugg... | This error suggests that the decoder needed for JPEG was not built along with ffmpeg. I believe enabling mjpeg is sufficient in order for it to work, but out of frustration I simply enabled everything and it worked.
I would suggest adding --enable-decoder=mjpeg to the configuration string and rebuilding the library wit... |
7,114,676 | 7,114,709 | Warning message purpose? | While compiling a while loop without a body, I saw this message:
warning: suggest a space before ';' or explicit braces around empty body in
'while' statement
Why should I put a space? Is it to make it clearer that my loop isn't really doing anything?
| Yes -- the usual convention is to put it on a line by itself, something like this:
while (*d++ = *s++)
;
A few people prefer to use things like:
while (*d++ = *s++)
{
/* intentionally empty */
}
|
7,114,797 | 7,126,161 | Is there a way to link my GCL Lisp file with a separate C++ program on Windows? | I have looked for some info on this and haven't found anything very helpful.
Background
What I have is GNU Common Lisp installed. I can create a Lisp file and compile it to a .o object file using the command:
gcl -compile <my lisp filename>
Once I have that .o file I use the command (using MinGW):
g++ -o myProgram.exe... | First of all, I'm not sure it is possible to call GCL compiled functions from C++ at all. Compare definitions of your CL's and C++'s functions:
(defun fib (x) ...)
and
int fib(int)
Second function is strictly typed, while first one takes and returns any object. So, what function should g++ search for in your temp.o ... |
7,115,027 | 7,115,111 | standard bucket or counting sort | I've always wondered why the C++ standard template library doesn't seem to have standard bucket/library (distribution) sorts. These seem underused in modern programming, apparently due to the requirement a way to convert an object to an integer to sort by. Both seem relatively simple to me, so why don't we have this ... |
Both seem relatively simple to me, so why don't we have this in the library?
Lots of things are simple. That's not a good reason to have them in a library.
I suppose the reason would be that std::sort is good enough for most cases.
|
7,115,162 | 7,115,257 | Windows C++ How can I call a blocking read from one thread to another? | I have two classes in C++ (Windows, Visual Studio 2010) each running a different thread, and I want to send messages between them in a simple way. The idea is that the main calls a read on class2, waits for class2 to get the data, and then main class receives it and continues - something like a socket, but between two ... | Sounds like you want a thread-safe queue to put your messages on.
Check out the 'Parallel containers and objects' in the Microsoft Parallel Patterns Library. That page has an example showing the use of concurrent_vector.
|
7,115,316 | 7,115,405 | Invalid Struct field values when passing it from managed to native code | I have a following problem:
C++ code:
typedef struct
{
double x;
double y;
double z;
} XYZ;
double Sum(XYZ xyz)
{
return xyz.x +xyz.y + xyz.z;
}
C# code:
[StructLayout(LayoutKind.Sequential)]
public class XYZ
{
public double x;
public double y;
public double z;
}
[DllImport("MyUnmanaged.dll", C... | You need to declare XYZ as a struct rather than a class. It should then marshal correctly.
|
7,115,459 | 7,115,533 | C++ rand and srand gets different output on different machines | I wanted to generate a random integer, so I used C++ rand(void) and srand(int) functions:
int main(){
srand(1);
cout << rand() << endl;
return 0;
}
OK, it suits my needs. Each time I execute it I get same result, which I like it!
But there is a problem. When I executed it on my computer I got 16807 as o... | Yes, rand() has different implementations; there's no requirement for them to be identical.
If you want consistent sequences across implementations and platforms, you can copy the sample implementation from the C standard section 7.20.2. Be sure to rename both rand and srand so they don't collide with the standard lib... |
7,115,735 | 7,115,889 | UNIX File Descriptors Reuse | Though I'm reasonably used to UNIX and have programmed on it for a long time, I'm not used to file manipulation.
I know that 0/1/2 file descriptors are standard in, out, and error. I'm aware that whenever a process opens a file, it is given a descriptor with the smallest value that isn't yet used - and I understand s... | Each file descriptor is local to the process. However, some file descriptors can refer to the same file - for example, if you create a child process using fork() it would share the files opened by the parent. It would have its own set of file descriptors, initially identical to the parent's ones, but they can change wi... |
7,115,807 | 7,116,154 | How to use your own class in glVertexPointer / glColorPointer / glNormalPointer | I have a class representing a vertex as follows:
class Vertex
{
public:
Vertex(void);
~Vertex(void);
GLfloat x;
GLfloat y;
GLfloat z;
GLfloat r;
GLfloat g;
GLfloat b;
GLfloat nx;
GLfloat ny;
GLfloat nz;
Vertex getCoords();
Vertex crossProd(Vertex& b);
void normalize();
Vertex operator-(Vertex& b);
Vertex& operato... | The byte arrangement of data in structs/classes (C++ considers them the same) is only guaranteed if that class is a plain-old-data (POD) type. Before C++0x, the rules for POD types were very strict. The class could not have constructors or destructors, of any kind. It also couldn't hold non-POD types. It cannot have vi... |
7,115,823 | 7,116,787 | Waiting for button press in Qt | I have a custom class inheriting from QDialog. I'm creating this dialog with function foo, and foo would like to continue doing its thing only when a certain button in the dialog is pressed. I was thinking of using signals and slots, but then how could I get foo to respond to a signal from another thread?
EDIT: basical... | Your foo() function could call wait() on a [QWaitCondition][1] object, then your button could call wakeOne() on the same object to cause the wait() to return.
That said, there is really no necessity for using multithreading to reimplement QInputDialog::getText(). You should be able to reimplement that functionality ... |
7,115,947 | 7,132,605 | Template "Adapters" in C++ | I am currently facing a problem dealing with template classes. In the codebase I am currently working with we have a line something like this:
Register<uint32_t>* myReg = static_cast<Register<uint32_t>*>(importItemPtr(someGlobalIdString));
where importItemPtr is responsible for returning a void* to an item from... | Try to use Bridge pattern where Implementor is a collection of common operations and specialization are ConcreteImplementors.
http://en.wikipedia.org/wiki/Bridge_pattern
Probably not best solution (overdesign), so please analyse it before use.
|
7,115,988 | 7,116,093 | is this a valid delete operation in c++? | I have a vector<some_struct&> array in my code, and whenever I want to add some object to my vector I use array.push_back(*new some_struct). now I'm wondering if I should delete every object in my array before clearing my array (using delete &array[i]) or not?
| vector<some_struct&> array is invalid, period.
The type (or types) with which you instantiate a Standard Library container must be object types. A reference type (like some_struct&) is not an object type.
By definition, "containers are objects that store other objects" (from §23.1/1 in both C++03 and C++0x). Referenc... |
7,116,025 | 7,116,082 | variadic templates - compile error | Could you help me in fixing the compile error in the following code:
#include <sstream>
#include <iostream>
using namespace std;
template<typename T, typename ...P>
class Mystrcat{
public:
Mystrcat(T t, P... p){init(t,p...);}
ostringstream & get(){return o;}
private:
ostringstream o;
void init(){}
v... | You're getting this error because there isn't a way to unpack your p into either init function. In your instantiation Mystrcat<char*, char *>, unpacking a P... will yield a single thing in the type: char*, which doesn't have an init with that signature (the instantiated version will have a void init() and void init(ch... |
7,116,030 | 7,116,164 | C++ to java, language equivalency questions | I've grown quite fond of some structures in C++, and I've recently been porting over some old school projects to java, but have run into a few snags that weren't resolved by simple google searches... So I figured that I'd ask here:
In C++ I'm quite fond of Stringstream, vector, list, and dequeue, but haven't been able... | For Stringstream you can use java.io.ByteArrayOutputStream
C++'s Vector<T> is basically the same as java.util.ArrayList<T>
The closest match for list<T> would be java.util.LinkedList<T> -- both are implemented as doubly linked lists (though if all you want is an ordered collection of elements you should probably use th... |
7,116,337 | 7,117,356 | How can I trigger a WSAOVERLAPPED event? (C++) | Note: The particular case I'm having troubles with is when lpCompletionRoutine is null and lpOverlapped is not.
I'm trying to write a packet sniffer. I'm hooking WSARecv and replacing it with my own code. If lpOverlapped is not null, I create my own LPWSAOVERLAPPED variable and call the real WSARecv. I receive and log ... | Agree with Eugene Homyakov, with one little addition. Actually there are 3 ways the OS may notify the process about overlapped I/O completion.
Setting the event specified by hEvent member of the OVERLAPPED structure
Invoking the completion routine (specified in the call to WSAxxxx).
Posting a completion to the complet... |
7,116,505 | 7,116,613 | Private inheritence and constructors | I have following problem:
want to inherit some class as protected (outside derived class i dont need any member or function from base class)
want to be able to access base constructor in some way
Here is an example (compile error):
class Animal
{
public:
explicit Animal(void){;}
};
class Dog: private Animal
{
pu... | As an alternative to reinterpret_cast, you may expose the base class with a method. If one day you decide to use composition instead of inheritance, it won't break your code:
class Dog: private Animal
{
public:
explicit Dog() {}
Animal * GetAnimal() { return this; }
};
int main(int argc, char *argv[])
{
Do... |
7,116,610 | 7,116,688 | Avoiding duplication of function definitions in template specializations | The class Widget has some functions that apply for all parameter types (common functions) and other functions that need to be specialized for given types (the uncommon functions).
g++ insists that the specialization for Widget should also define common_fn() and not just uncommon_fn(), but that defeats the purpose of us... | #include <assert.h>
template<typename Type> struct Widget
{
Widget() {}
char common_fn() { return 'a'; }
int uncommon_fn() { return 1; }
};
template<>
int Widget<char>::uncommon_fn() { return 2; }
int main()
{
Widget<char> WidgetChar;
assert( WidgetChar.common_fn() == 'a' ); // OK
assert( Wid... |
7,117,069 | 7,117,257 | Avoiding duplication of function definitions in partial template specializations when using traits | How does one share common_fn() among all specializations (for Widget<A<T> > and Widget<B<T> >, no matter what T is) in the code below?
#include <cassert>
struct Afoo {};
struct Bfoo {};
template<typename T> struct A { typedef Afoo Foo; };
template<typename T> struct B { typedef Bfoo Foo; };
template<typename Type> s... | It's a little unclear what you're aiming for, in particular whether uncommon_fn is really as simple as illustrated, or might be more.
But anyway, for the example code given, consider …
#include <cassert>
#include <typeinfo>
struct Afoo {};
struct Bfoo {};
template< class T > struct A { typedef Afoo Foo; };
template< ... |
7,117,122 | 7,117,140 | Invoke and control GDB from c++ | Is there any way to invoke GDB and control, access it from c++ program?
| Yes. Execute it with redirected input/output and simply control it through the pipes.
EDIT:
It depends on where you want to do it. On Windows you can use the following: http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx
On *nix, the steps described in Linux Pipes as Input and Output SO answer should do ... |
7,117,293 | 7,117,437 | or C++: VS2010 multiplication operator being mistaken for a null pointer | I basically have exp>=level*10 in an else if expression, where level is a variable and 10 is a constant number. The code compiles completely fine without any errors, and it even worked after being compiled, until recently. now, whenever it compiles and executes, it gives me an error saying "invalid null pointer" and it... | This program reproduces your problem (when compiled with MSVC with runtime that supports debugging):
#include <string>
#include <iostream>
int main()
{
using namespace std;
string s = 0;
cout << s << endl;
}
The problem is that a std::string is initialized with a nullpointer.
EDIT: oh, forgot to mention... |
7,117,300 | 7,117,398 | what's the advantage of message queue over shared data in thread communication? | I read a article about multithread program design http://drdobbs.com/architecture-and-design/215900465, it says it's a best practice that "replacing shared data with asynchronous messages. As much as possible, prefer to keep each thread’s data isolated (unshared), and let threads instead communicate via asynchronous me... | Message passing is useful for exchanging smaller amounts of data, because no conflicts need be avoided. It's much easier to implement than is shared memory for intercomputer communication. Also, as you've already noticed, message passing has the advantage that application developers don't need to worry about the detail... |
7,117,337 | 7,117,662 | Looking for a Qt open source project which is similar to Windows Paint | I'm searching a Qt open source project for reference. Is there such a project like Windows Paint?
| What Qt gives you in the base examples is the "Scribble" sample, which is supposed to get you started:
http://doc.qt.nokia.com/latest/widgets-scribble.html
But if you wanted something that's going to have shape tools, color palettes, and other features then there's KolourPaint, but it is dependent on more than just Qt ... |
7,117,567 | 7,117,605 | Boost Circular Buffer, how to make it call some function when it is filled? | I like Boost Templated Circular Buffer Container, but how to get when it was filled 100%?
#include <boost/circular_buffer.hpp>
int main() {
// Create a circular buffer with a capacity for 3 integers.
boost::circular_buffer<int> cb(3);
// Insert some elements into the buffer.
cb.push_ba... | You can wrap the circular_buffer instance into its own class and implement event handling on top of it.
class MyCircularBuffer
{
public:
MyCircularBuffer() : buffer(3) {}
void PushBack(int i)
{
buffer.push_back(i);
if(buffer.size() == 3)
{
// buffer is full!
}
... |
7,117,573 | 7,117,645 | Parsing only numbers from istream in C++ | I have a bunch of input files that look like the following:
(8,7,15)
(0,0,1) (0,3,2) (0,6,3)
(1,0,4) (1,1,5)
I need to write a function that parses these inputs one number at a time, so I need to be able to separate the input by numbers, e.g.: 8, then 7, then 15, then 0, another 0, so on.
The only way I've thought of ... | Here's some code, you can adapt to meet your precise needs
for (;;)
{
int ch = in.get();
if (ch == EOF)
break;
if (isdigit(ch))
{
int val = ch - '0';
for (;;)
{
ch = in.get();
if (!isdigit(ch))
break;
val *= 10;
val += ch - '0';
}
// do something with val
... |
7,117,693 | 7,119,099 | object orientation, inheritance, and composition in c++ | There are 4 classes: A, B, C, and D. Class A "HAS A" B, and class C "HAS A" D. As it happens, C "IS A" A, and D "IS A" B. What's the best way to model these relationships in C++?
The B that A has is the same D that C has.
Example: A building has an entrance, and a house has a door. A house is a building, and a door ... | I think there is a flaw in your design. If I understand correctly, you want to restrict the type of a base class member variable:
struct Entrance {};
struct Door : public Entrance {};
struct Building
{
Entrance * entrance; // raw pointer just for the sake of clarity
};
struct House : public Building
{
// Buil... |
7,117,844 | 7,117,876 | Pointer address does not change in a link list | My problem is q->next always prints the same address, but I assigned q = &x;. Why it is not printing different addresses?
#include <stdio.h>
class Node
{
public:
int val;
Node *next;
Node(int v,Node *p) { val=v, next=p; }
};
int main()
{
Node head(0, NULL);
Node *q = &head;
int i = 5;
w... | This has to do with the way x is allocated: It is a local variable inside the main function. That means it is allocated on the stack, at a specific position. You are reusing the same piece of memory all the time. Instead, try allocating memory for new nodes (new).
|
7,117,867 | 7,118,527 | Nested Pass by Reference | I need to have a nested pass by reference.
EDITED TO INCLUDE ACTUAL CODE
Exact error is:
no matching function for call to ‘CLItem::getValue(std::string*&)’
Complete error is:
App/CycCmdLine.cpp: In member function ‘std::string CycCmdLine::getEnvironment()’:
App/CycCmdLine.cpp:245: error: no matching function for call... | If we look into this part of the message
./../CmdLine/CmdLine.h: In member function ‘bool CmdLine::getValue(std::string, T&) [with T = std::string*]’:
App/CycCmdLine.cpp:384: instantiated from here
./../CmdLine/CmdLine.h:237: error: no matching function for call to ‘CLItem::getValue(std::string*&)’
It seems to say t... |
7,118,034 | 7,118,234 | How to make thread safe Log class that supports `<<` operations? | So I have such log class:
#include <iostream>
#include <sstream>
#include <boost/circular_buffer.hpp>
#include <boost/foreach.hpp>
class FlushInternal;
class Log
{
public:
static FlushInternal* endl;
Log(int log_length)
{
i = 0;
messages_buffer = new boost::circular_buffer<std::string>(l... | The approach linked by trojanfoe is pretty much the canonical one. Basically create some temporary thing for the leftmost << operator, accumulate everything, and output the message in the destructor for the temporary thing.
The only question is the exact mechanics of this accumulator. The example used ostringstream, ... |
7,118,262 | 7,118,332 | Compilation errors with stdio.h in VC++ 2008 | I have a number of projects created in VC++ 2008.
However I'm getting the following error when trying to build every single one of them:
1>Compiling...
1>main.cpp
1>c:\program files (x86)\microsoft visual studio 9.0\vc\include\stdio.h(413) : error C2061: syntax error : identifier '_In_kpt_'
1>c:\program files (x86)\mic... | You have a corrupted stdio.h file.
The token on line 413 is supposed to be _In_opt_, not _In_kpt_.
And line 422 is supposed to be an #endif, not an #efdif.
I'd reinstall VS 2008 (maybe after checking things out pretty carefully in case your hard drive is failing or something) in case other files are subtly corrupted.
|
7,118,323 | 7,118,360 | What's the requirement for storage duration of temporaries? | Consider the following code:
class Test() {
public:
Test()
{
memset( buffer, 0, sizeof( buffer ) );
}
void Process()
{
printf( buffer );
}
private:
char buffer[1000];
};
int main()
{
Test().Process();
char buffer[1000] = {};
print( buffer );
return 0;
}
... | The lifetime of the temporary (unless bound to a const&) extends to the end of the full expression. In your case the first line in main. The compiler is allowed to reuse the same memory, but whether it does or not is an implementation detail (i.e. quality of implementation)
12.2 [class.temporary]
/3 [...] Temporary ob... |
7,118,372 | 7,118,570 | Make printf write faster to the Windows commandline | I'm analyzing some high resolution midi data. I'm writing it to the stdout but since there is so much data coming in it takes seconds for them all to display after I did the actual action.
Currently this line writes to the commandline:
std::vector<unsigned char> message;
...
printf("W 1 = %03d, W 2 = %03d, W 3 = %03d \... | There's a good chance that this is a video driver issue - video card manufacturers probably don't always pay a lot of attention to console window performance. I've had rigs with painfully slow - I mean tooth-extraction painful - console windows that had probably 100 times improvement in that area by updating the video... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.