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 |
|---|---|---|---|---|
5,610,785 | 5,613,830 | How to tell QThread to wait until work is done ,and then finish? | I have a simple application that uses one worker thread.
This worker thread is started and initializes DownloadManager, which is responsible for downloading files from the net.
In my main application class I have the finished() SIGNAL on the thread that is emitted before the DownloadManager finishes.
My question is how... | You can use QThread::exec() call to run your thread in the event loop. The thread will run it until you tell your thread to exit by calling QThread::exit(). So some sample code can look like this:
void DownloadWorker::run()
{
DownloadManager* pDownloadManager = new DownloadManager(this);
connect(pDownloadManag... |
5,610,940 | 5,610,961 | Can Facebook HipHop (PHP to C++) be compiled and run on Windows | Has someone tried to achieve that?
http://developers.facebook.com/blog/post/358
| Taken from the link you've given:
HipHop for PHP isn't technically a compiler itself. Rather it is a source code transformer. HipHop programmatically transforms your PHP source code into highly optimized C++ and then uses g++ to compile it.
You'll have to replace the g++ compiler for one that runs on windows like mi... |
5,610,981 | 5,611,242 | Extract base class pointer | I was told that I can extract reference to base class from any boost::python::object.
The simple code looks like:
// c++:
class Base {};
// Export Base into python module
// python:
class Der(Base):
pass
//c++:
boost::python::object obj; // It points to some Der class object made from python
boost::shared_ptr<Obj... | So, using this thread I've managed out my question. First of all, my Base class was exported into python this way:
bp::class_<Base, boost::noncopyable>("Base", bp::no_init)
I had to remove bp::no_init. Why? Look at next update (the answer in stackoverflow post I gave before):
class Der(Base):
def __init__(self):
... |
5,611,140 | 5,611,846 | Image Processing - Rotation and Optical Character Recognizion | Good Morning everybody,
Today I wanna concern about the topic "Image Manipulation in C++".
So far I am able to filter all the noisy stuff out of the picture and change the color to black and white.
But now I have two questions.
First Question:
Below you see a screenshot of the image. What is the best way to find out ho... | The usual name for the problem in your first question is "Skew Correction"
You may Google for it (lot of references). A nice paper here, showing for example how to get this:
An easy way to start (but not as good as the previously mentioned), is to perform a Principal Component Analysis:
|
5,611,149 | 5,611,173 | C++ library for storing settings in XML | Before I start writing by own settings library I though I would try to find an existing one. I've googled and found plenty for C# or MFC but nothing that uses plain C++/STL. I'd like something that allows access via keys such as:
mySettings["Root"]["Subsection"]["Value"].Value
Or something along those lines. Is there ... | There is TinyXML and pugixml
PugiXML does have XPath support
|
5,611,188 | 5,617,519 | How to use MurmurHash 64 in Objective-C? | I need to Hash a NSString using murmurhash i am forced to do that because the other team is doing so, I need to use the 64-bit key length on x86 platform, have anyone implemented or used murmurhash in objective-C?
Murmurhash 64 is a .cpp file and i can't get it compiled in iOS SDK 4.3, also tried to rename it to .mm bu... | For all those who will come to look for the correct answer, here is the deal:
MurmurHash64.h class
careful I have changed the typedef
// MurmurHash, by Austin Appleby
typedef unsigned long long uint64_t;
uint64_t MurmurHash64B ( const void * key, int len, unsigned int seed );
MurmurHash64.m class
#include "MurmurHa... |
5,611,254 | 5,611,272 | linux/kernel.h : No such file or directory | I am going to write a Hello World module in Ubuntu 10.10 (with the kernel 2.6.35-28-generic). Headers are located:
/usr/src/linux-headers-2.6.35-28-generic
hello.c:
#include <linux/kernel.h>
#include <linux/module.h>
int init_module(void)
{
printk("Hello, world\n");
return 0;
}
void cleanup_module(void)
{
... | Do you have /usr/src/linux symbolic link to your /usr/src/linux-headers-2.6.35-28-generic ?
If not then create one using following commands
# cd /usr/src
# ln -sfn linux-headers-2.6.35-28-generic linux
|
5,611,669 | 5,611,692 | arc4random in wxDev C++ | im trying to add arc4random into my C console-based project.
Basically im including the .c file in my project and then a method call as:
#include <stdio.h>
#include <stdlib.h>
#include "arc4random.c"
//Define globals
int r;
int main(int argc, char *argv[]) {
r = (arc4random() % 100);... | Including C files is not a good practice in C programming, except in some cases with automatically-generated code.
Instead, all the source files should be passed to the compiler and you should only include header files which contain function prototypes and type definitions.
|
5,611,831 | 5,616,145 | (Linking)Problem in Berkeley DB in Visual studio 2010 | i am traying to start using Berkeley DB, i downloaded the latest version of DB available here: Berkeley DB 5.1.25.msi Windows installer, with AES encryption
after the installation i started Visual studio 2010 and i did the followng:
Project -> "project name" Properties
-> VC++ Diretories -> include Directories
i ... | You need to link the .lib's included with Berkley DB. There is probably a C:\Program Files\Oracle\Berkeley DB 11gR2 5.1.25\lib folder. You will need to add this folder, or possibly an appropriate sub folder. For example, there might be a Windows folder with x86 and x64 sub folders. You will need to add the appropriate ... |
5,612,017 | 5,612,044 | Difference between gcc-4.0.0-8 and gcc-4.3.2 | SPOJ and Codechef have both of them in list of accepted languages. What is the so big difference between them that they have to be distinguished?
| For C++, they aren't binary compatible with each other, for one thing.
There's a lot of openmp function that arrived between 4.0 and 4.3 for another.
|
5,612,058 | 5,612,064 | Heap memory allocation crash with std::wstring | I have a big problem with std::wstring memory allocation. The program crash when I try to use this code:
size_t size;
mbstowcs_s(&size, NULL, 0, buffer, _TRUNCATE);
wchar_t *buffer2 = (wchar_t*)malloc(size + 1);
mbstowcs_s(&size, buffer, buffer_size, buffer, _TRUNCATE);
buffer2[size] = '\0';
std::wstring data(buffer);... | wchar_t *buffer2 = (wchar_t*)malloc((size + 1) * sizeof(wchar_t));
^^^^^^^^^^^^^^^^^
malloc allocates a number of bytes - you wan't a number of wchar_t's
If you're using c++, the correct way is:
wchar_t *buffer2 = new wchar_t[size+1];
|
5,612,182 | 5,612,287 | Convert string with explicit escape sequence into relative character | I need a function to convert "explicit" escape sequences into the relative non-printable character.
Es:
char str[] = "\\n";
cout << "Line1" << convert_esc(str) << "Line2" << endl:
would give this output:
Line1
Line2
Is there any function that does this?
| I think that you must write such function yourself since escape characters is a compile-time feature, i.e. when you write "\n" the compiler would replace the \n sequence with the eol character. The resulting string is of length 1 (excluding the terminating zero character).
In your case a string "\\n" is of length 2 (ag... |
5,612,210 | 5,612,269 | Error while using for_each | I have the following 2 functions in my code:
bool num()
{
return 0;
}
void setDFS()
{
int i = 0;
project3::Graph<string, string> g1;
std::for_each(g1.Vertice1.begin(), g1.Vertice1.end(),num);
}
What the function does is for each Vertice in vector Vertice1, it has to set its number to 0 for now. Once... | for_each algorithm receives a unary function which should have the following signature:
void function(T&);
where T is the type of element of g1.Vertice1 vector:
template <class VertexType, class EdgeType>
void num(project3::Vertex<VertexType, EdgeType>* v) {
*v = 0; // <- Maybe v->set(0,0,0)
}
|
5,612,260 | 5,627,962 | Variable arguments in _stdcall, C++ / Inline ASM | I'm in a situation where I have to mock up a _stdcall function using C++ and inline ASM, but which uses a variable number of arguments. Normally it wouldn't know how many arguments to pop from the stack when it returns control to its parent, so wouldn't work, but I'm hoping to tell it via a global variable how many par... | You can do something like the following (hacked up code):
static int NumberOfParameters = 0;
__declspec(naked) void GenericCallback()
{
// prologue
__asm push ebp
__asm mov ebp, esp
// TODO: do something with parameters on stack
// manual stack unwinding for 2 parameters
// obviously you woul... |
5,612,331 | 5,612,343 | what's a c++ equivalent of a generic? | suppose i'm implementing a polymorphic tree data structure that can take on data of any type...
Tree<Int> or Tree<String> or Tree<Object>
but I'm implementing it in C++....how would I specify that the tree can contain an arbitrary type similar to generics in Java
also is there an equivalent of Java's Object object in... | The nearest equivalent of Java's generic is template in C++. Its not equivalent as such, if strictly speaking. But that is what you've in C++. So to suit your need, you've to work a little bit so that you can write equivalent code in C++.
Here're few links to some articles that compare C++ template with Java generics:... |
5,612,358 | 5,613,181 | Audio/MIDI C++ library for a real-time application | As I've already said in another thread, I'm working on a project related to real-time graphical programming for audio (something like Pure Data, Max/MSP, Reaktor).
I did a day of research on Internet, looking for a good (maintained, well documented and highly portable) C++ library for low level interaction with audio a... | I've used both PortAudio/PortMidi and Juce with great results on both. I'm in the process of switching a project over from PortMidi to Juce, because for my uses all that other app framework stuff ends up being incredibly useful (and in my experience, it's rock solid.). YMMV.
|
5,612,486 | 5,612,508 | When is a function try block useful? | I'm wondering when programmers use function try blocks. When is it useful?
void f(int i)
try
{
if ( i < 0 )
throw "less than zero";
std::cout << "greater than zero" << std::endl;
}
catch(const char* e)
{
std::cout << e << std::endl;
}
int main() {
f(1);
f(-1);
return 0;
}
Out... | You use it in constructors to catch errors from initializers. Usually, you don't catch those errors, so this is a quite exceptional use.
Otherwise, it is useless: unless I'm proven wrong,
void f() try { ... } catch (...) { ... }
is strictly equivalent to
void f() { try { ... } catch (...) { ... } }
|
5,612,584 | 5,613,004 | Qt creator C++, adding many labels to statusbar | I would like to add 3 items to statusbar. Shouldn't each be in its own label?
Is that possible? When I tried to add a second label, it gave me an error.
File mainwindow.h,
QLabel *m_statusLabel;
QLabel *m_pointLabel;
File mainwindow.cpp,
statusBar()->addWidget(m_statusLabel);
statusBar()->addWidget(m_pointLabel);
It ... | I found the problem. I forgot to create QLabels, so I added this:
m_statusLabel = new QLabel(this);
m_pointLabel = new QLabel(this);
|
5,612,730 | 5,612,751 | c++ list no type error | so I had this code:
#include <list>
void j(){
list<int> first;
}
but then I get this error:
error: ISO C++ forbids declaration of `list' with no type
error: expected `;' before '<' token
what did I do wrong lol....
| Types and functions in the C++ Standard Library are in the std namespace.
This means that the type you are looking for is std::list<int>.
You can avoid having to write std:: by using either of the following in the same scope:
using namespace std;
or
using std::list;
(Now you can just write list<int>, because the typ... |
5,612,776 | 5,612,948 | C++ pair delete error | *Update: * Finally I find the problem. The problem is like this:
pair<int,int> *findPair(){
pair<int,int> *t = new pair<int,int> [10];
for(int i=0;i<11;i++) // error here
{
t[i].first =1;
t[i].second =2;
}
return t;
}
int main() {
pair<int, int> * tt = findPair();
tt[1].firs... | I copied your code into a .cc file (with the right #include), and this code works just fine. Are you sure this is where the segmentation fault is at?
If you are using linux, and have no core file, use "ulimit -c unlimited".
Then you can load the core file in gdb to check where the error takes place.
|
5,612,791 | 5,612,847 | c++ template and header files | So, I heard that C++ templates shouldn't be separated into a header (.h) and source (.cpp) files.
For instance, a template like this:
template <class T>
class J
{
T something;
};
Is this true? Why is it so?
If because of that I'm gonna have to put both declaration and implementation in the same file, should I pu... | Headers.
It's because templates are instantiated at compile-time, not link-time, and different translation units (roughly equivalent to your .cpp files) only "know about" each other at link-time. Headers tend to be widely "known about" at compile-time because you #include them in any translation unit that needs them.
R... |
5,612,944 | 5,613,662 | Can't understand multi_index | class ObjectStorage
{
private:
std::string objName;
int zIndex;
// Reference for the Object interface
boost::shared_ptr<Object> mCppObject;
// Reference for the Python interface
boost::python::object mPythonObject;
public:
ObjectStorage(const std::strin... | In your case multi_index_container contains instances of ObjectStorage objects. So you can iterate in any order through it and call any function of ObjectStorage class.
For instance to iterate using tag_py tag:
ObjectWrapperSet ow_set;
ObjectWrapperSet::index_const_iterator<tag_py>::type it = ow_set.get<tag_py>().begi... |
5,613,035 | 5,725,451 | C++ Stream serialization | Currently I'm trying to implement some kind of object stream, similar to the structure that exists in java.
Using the "Stream Socket API" by Rob Tougher it's easy to use the stream insertion operator<<.
This would lead to the problem that every serializable object would require every single class to overload the same o... | Java serialization relies on reflection to automatically discover and serialize class fields. In C++, your options are:
Write input and output functions manually for each class. boost::serialization uses this approach.
Declare serializable entities in a separate language and compile that language to C++ with automatic... |
5,613,041 | 5,614,445 | Member function in Eigen math library for vector magnitude | I have been trying to find a method that computes the magnitude of a vector in Eigen and I was not able to. Can somebody provide me with the function name of just if it doesn't exist?
I can create a global method that does the job but I prefer not to.
| You want .norm(). Note that there's also .squaredNorm(), .normalized() and .normalize().
|
5,613,054 | 5,613,091 | Qt creator C++, setting text of Statuslabel | m_pointLabel->setText(tr("Vertices: " . m_drawingWidget->getPointListSize()));
m_pointLabel->setText(tr("Vertices: " . m_drawingWidget->getLineListSize()));'
I am trying to set text, but I am getting the following errors.
request for member 'm_drawingWidget' in "Vertices: ", which is of non-class type 'const char [11... | . is the concatenation operator in PHP, but C++/Qt is not PHP.
Use:
tr("Vertices: %1").arg(m_drawingWidget->getPointListSize())
|
5,613,193 | 5,613,300 | C++ Simple image collision | I have done a bunch of searches but i was unsure what answers apply to my problem. Im making a simple game where on a timer a image moves down while you move your "character" left and right. How would i go about making it subtract 1 from a variable when they collide? I can post code if needed
| Are you talking about collision detection? I would probably need code, but I am assuming you know the width and height, x and y position of your objects, and that they are rectangular. Checking if they intersect should be trivial. Check if object 1's (y + height) is greater than object 2's (y + height) and that object ... |
5,613,432 | 5,613,464 | C++ "infinite" length text | my task is to make a program that can store arbitrary long text in c++.
I have no idea how to solve this.
Also, you cannot use STL.
someone please help
|
allocate initial buffer (malloc())
store data into buffer until full (strcpy(), strcat(), memcpy()...)
reallocate to a bigger buffer (realloc())
goto 2
|
5,613,514 | 5,613,556 | Not able to use Directory::getFiles() directly in the code | I am trying to get few files from a path of specific pattern and for this I am using the command below which is giving me an error:
std::vector<std::string> cppFiles;
cppFiles = System::IO::Directory::GetFiles(path, "*.cpp" );
Error is on "System" and it says:- name followed by :: must be a class or namespace name.
I ... | You are obviously not including the relevant header.
|
5,613,536 | 5,640,922 | TVN_SELCHANGING not received | I have a WTL81 app. CMainFrame has a child CPaneContainer, that has a child window CTreeViewCtrl. The problem is CTreeViewCtrl doesn't receive TVN_SELCHANGING message.
I have "spied" CTreeViewCtrl and his parent (CPaneContainer) and no notification code is received.
CMainFrame is implemented from public CFrameWindowI... | Solved. My problem was that treeview was multi-selct and that kind of tree doesn't send TVN_SELCHANGING notifications
|
5,613,649 | 5,623,054 | How to know the status of a SSL socket in Boost asio | In normal connections, asuming a socket:
boost::asio::ip::tcp::socket socket_;
it's possible ask the socket status with:
if (socket_.is_open()) { ... }
But instead, in secure connections, asuming a socket:
boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket_;
There is not an is_open() method for the socke... | boost::asio::ssl::stream<boost::asio::ip::tcp::socket> socket_;
if ( socket_.lowest_layer().is_open() ) {
// do something great
}
see the documentation for more information.
|
5,613,775 | 5,613,805 | Why is the base constructor called? | Alright, I have a very basic question, so please go easy on me.
In the following code:
#include<iostream>
class base
{
public:
base() { std::cout << "Base()" << std::endl; }
};
class derived: base {
public:
derived() { std::cout << "Derived()" << std::endl; }
};
... | Constructor of the base class is called to initialize base class subobject that contained in the derived. This is how inheritance works, this makes it easier to follow the Liskov substitution principle.
Consider the following:
class base
{
public:
base() : x(10) { std::cout << "Base()" << std::endl; }
private:
int... |
5,613,982 | 5,614,037 | Initializing a class using malloc | I am working on a toy language for avr using C++ as the intermediate language, Problem is avr-gcc does not have new implemented. All my object derive from the class Object which has virtual methods when I create say a float object with malloc using instructions from,
Can I implement the Factory Method pattern in C++ wi... | It appears that new as a language construct is supported, but the operator new code that underlies it and does the actual allocation isn't implemented.
It should be pretty easy to fix that by providing your own implementation for operator new in your source code:
In some header file that's included in any file needing ... |
5,614,018 | 5,614,051 | Am I calculating my FPS correctly? | So I was wondering if I'm calculating my FPS correctly:
Uint32 delayFrom(float startTime, float endTime){
return(endTime - startTime );
}
int main(){
int numFrames = 0;
Uint32 startTime = SDL_GetTicks();
while(!done){
frameTime = 0;
float fps = ( numFrames/(float)(SDL_GetTicks() - star... | int main() {
int numFrames = 0;
Uint32 startTime = SDL_GetTicks();
while (!done) {
++numFrames;
Uint32 elapsedMS = SDL_GetTicks() - startTime; // Time since start of loop
if (elapsedMS) { // Skip this the first frame
double elapsedSeconds = elapsedMS / 1000.0; // Convert to seconds
double ... |
5,614,064 | 5,614,081 | Converting from 3D to 2D coordinates question | Im using OpenGL with c++ to make a game. and right now, im wondering how i would be able to turn 3D coordinates into 2D positions for example: drawing a 2D health bar over a 3D model's head, or something along those lines. xD
so anyways, im wondering how i would be able to set this up where it can be used in SFML. righ... | Since you're using OpenGL, I'd suggest gluProject for mapping from 3D to 2D and gluUnProject for mapping from 2D to 3D (note @ChrisF's comment on unprojecting).
Though I gotta admit, I got no real experience with OpenGL, I just know the terminology for what you wanted and googled for it. :)
|
5,614,222 | 5,614,733 | Parse double precision IEEE floating-point on a C compiler with no double precision type | I am working with an 8-bit AVR chip. There is no data type for a 64-bit double (double just maps to the 32-bit float). However, I will be receiving 64-bit doubles over Serial and need to output 64-bit doubles over Serial.
How can I convert the 64-bit double to a 32-bit float and back again without casting? The format f... | IEEE specifies five different rounding modes, but the one to use by default is Round half to even. So you have a mantissa of the form 10001100 11001100 11001100 11001100... and you have to round it to 24 bits. Numbering the bits from 0 (most significant), bit 24 is 1; but that is not enough to tell you whether to round... |
5,614,252 | 5,614,304 | How can a global function call a specific function in a class? | I have a global function and a class containing few member functions as per below:
Function Vert() is printing blank on console.
While debugging I found that the values at Vertice1[i] is null so may be its coming blank on the console. But dispFileName does contain the values.
Am I passing the values correctly to the v... | After the first for loop ends, you've got a vector of pointers to Vertex objects. But the actual Vertex objects have gone out of scope, since they're local to the first for loop. So your pointers are invalid at that point, and you're getting random results (in this case, empty strings).
Here I'm assuming that Graph<T, ... |
5,614,254 | 5,614,346 | How to iterate multi_index | here is my multi_index code:
struct tag_type {};
typedef boost::multi_index_container<ObjectStorage,
bmi::indexed_by<
// Type
bmi::ordered_non_unique<
bmi::tag<tag_type>,
bmi::const_mem_fun<ObjectStorage, std::string, &ObjectStorage::ge... | Did you try this?
ByTypeIt end = mObjectsByTypeViewer.end();
|
5,614,303 | 5,614,326 | Why aren't case statement inside a switch being indented by some IDEs? |
Possible Duplicate:
Why don't people indent C++ access specifiers/case statements?
I have a syntax question... not about the how, but rather the why. Many IDEs such as Eclipse and Qt Creator automatically indent a switch like this:
Day randomDay = getRandomDay(); /* returns 'enum Day' */
switch (randomDay) {
defaul... |
Code styles are like assholes. Everyone has one but only few people like the ones of other people.
This applies here, too. Some people liked it and thus did it when writing the indentation logic for an IDE. Most good IDEs have an option to configure this behavior though.
A possible reason for this style is that it se... |
5,614,412 | 5,614,423 | c++ template problem | i have a class which has a template by other purposes:
template<class t>
class MyClass {
public: //of course public...
t foo;
std::string text;
}
and i have another class which method get all kind of these class through the arguments, and want to store the pointer in an array. The class dont want to access... | The simplest method would be to make that function a template as well:
template <class t>
void bar(MyClass<t>& m) {
// ...
}
Note that that should probably be const MyClass<t>&, because you don't need to modify it.
Your new code is meaningless. There is no such that as an object of type MyClass, because MyClass i... |
5,614,413 | 5,614,458 | Qt creator C++, void value is not ignored as it ought to be | QList<QPoint*> DrawingWidget::getCloseLinesById(int m_x, int m_y) {
QList<QPoint*> lines;
// HERE I APPEND ABOUT 5 ITEMS
return lines;
}
The appending works here. It only gives me a few warnings, but it still compiles. The warning is.
taking address of temporary
But this
void DrawingWidget::mouseMoveEv... | You didn't state what exactly is your question. But you are using extra * in your errored lines:
points[i]->setX(event->x());
Also, you didn't show how you append to the list. My guess is the warning is from you assigning addresses of some computed QPoints. It will crash even if you get it compiled. Just use QList<QPo... |
5,614,635 | 5,615,591 | Qt Creator, C++, mouse over function | I want to change the color of an ellipse when I move my mouse over it.
But I haven't found anything from reference and auto-complete from Qt Creator.
Do you guys know how to do it?
Some of my code:
void DrawingWidget::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.fillRect(event->rect(), Qt::w... | I think what you are looking for are enter and leave events.
|
5,614,826 | 5,614,848 | Debugging "one line" methods | imagine (in header file):
int getInt() { return m_intValue; }
and
int getInt()
{
return m_intValue;
}
how can I debug first example, to see m_intValue?
In example 2, I can set breakpoint at line one, press F10(step over) and then see (after hovering m_intValue) what is in m_intValue. Or just add BP at return m_i... | You'll get the breakpoint set at the wrong code. It breaks on the function entrypoint, the this variable won't be initialized yet. You definitely want to favor the 2nd coding style if you want to debug these accessors. Which you shouldn't, it doesn't have a bug.
If you really need to inspect the object with the code... |
5,614,979 | 7,622,407 | Python SIP expose function | I'm writing a Python module for some C++ code using SIP. However whilst I can easily expose classes, I cannot find a way to expose standalone functions.
Here is my header file defining the functions that I wish to expose to Python: ProxySettings.h
#include <Windows.h>
#include <Wininet.h>
bool SetConnectionOptions(con... | Try this:
%Module ieproxy 0
%UnitCode
#include <ProxySettings.h>
%End
bool SetConnectionOptions(const char * proxy_full_addr);
bool DisableConnectionProxy();
|
5,615,094 | 5,615,124 | How do I assign a certain value from an object to a long variable? | Example:
long a;
BoundedCounter e;
So I want to assign the value of the private variable counter in the class to a.
a=e;
Tried using this:
long int & operator=(long b)
{
b=counter;
return b;
}
and
long int & operator=(long b, BoundedCounter &a)
{
b=a.getCounter();
return b;
}
Which return a compile er... | operator= is unsuitable here as the left-hand side of the assignment is a primitive type (and you cannot define operator= for primitive types). Try giving BoundedCounter an operator long, e.g.:
class BoundedCounter
{
public:
// ...
operator long() const
{
return counter;
// or return getCoun... |
5,615,165 | 5,615,834 | Should a button consume mouse events? | Right now, my scrollbar is made up of 3 buttons (its children). The buttons currently consume mouse down, up, click, and drag. The scrollbar then hooks into these 3 buttons and does what it wants them to do. Therefore, I do not use the new bubble-up-the-stack feature of my GUI in this scenario.
I'm still not quite clea... | In this case the 3 buttons (I presume up, down, and slider) don't have enough information to do anything on their own; the best they can do is interact with the main scrollbar control and tell it what modifications it should make. In that case it might just be cleaner to have the scrollbar do all the message processing... |
5,615,199 | 5,615,315 | C++ Switch Statement inputs | I am writing a C++ program that prompts the user for an input and then keeps track of how many times that input is entered. I am currently using a do-while loop and a switch statement. The part I am having trouble with is the switch statement. I can't figure out how to keep track of how many times an input is entere... | You'll probably want to use a std::map<int,int>. Here's why.
Let's look at alternatives, starting with the obvious:
int count0;
int count1;
int count2;
int count3;
int count4;
...
switch(input) {
case 0: ++count0; break;
case 1: ++count1; break;
case 2: ++count2; break;
case 3: ++count3; break
case 4: ++count4; break... |
5,615,239 | 5,615,336 | C++ strlen for the String class | How does the C++ length() method work for the std::string class? Thanks.
| The std::string class has several constructors, including one that takes both a const char* raw C string and a size_t length, and another that takes just a const char* raw C string. For the former, the provided length is stored, and for the latter, the length is computed once by invoking strlen or by performing an equi... |
5,615,463 | 5,615,474 | Does g++ compilation order matter? | I noticed that I was able to compile a child class before a parent class with g++. Is there any need to compile in a specific order, with consideration to dependencies?
| Linking order can matter; compilation order does not.
|
5,615,469 | 5,615,991 | Where to put pre-built binaries with automake? | I am writing this question in part based on a related question on helper-scripts.
I have a C++ software system built with autotools. For a small part of its functionality, my system uses a closed-source pre-built binary: AMPL. I'm a freely-available student version of their software. Suppose the name of the AMPL binary... | I'd install it in $(pkglibexecdir):
pkglibexec_PROGRAMS = ampl-student
# If you need to know the path in your code
AM_CPPFLAGS = -DPKGLIBEXECDIR=\"$(pkglibexecdir)\"
It's not really a user program, so this installs it somewhere out of the way. By default, this is going to be $(prefix)/libexec/$(package).
|
5,615,496 | 5,616,368 | Are container.end() and container.size() inlined? | I typically get into the discussion with others and I'm not able to confirm the behavior - if the container.end() and container.size() functions are inlined. For e.g. if we have a for loop as such:
for (vector<int>::iterator it=v.begin(); it!=v.end(); ++it) {
//...
}
for (size_t k=0; k < v.size(); ++k) {
//...... | All template functions are by definition inline functions. The compiler may choose to make them callable functions, especially if it's a debug mode compilation, but the most likely outcome is for the code to be inlined.
It's possible but unlikely that a temporary variable will be automatically created. How does the com... |
5,615,540 | 5,616,833 | Looking for a C++ code prettifier that will remove empty lines | I've just taken over a large, poorly formatted mass of C++ code.
I'm looking for a code prettifier with two specific features.
Remove superfluous access modifiers
Clean up white space in a nice way. eg. leave blank lines between
functions, collapse multiple blank
lines into one within functions,
remove blank lines bet... | See artistic style. I've used it on a medium-sized code-base without creating any problems. It can do a variety of source transforms on whitespace, indentation and so on.
Just make sure you back up your code (source control) while you experiment with the many, many options. The defaults are somewhat surprising...
|
5,615,888 | 5,615,896 | Error for getters and setters | I have a vector of vertices and I wish to set vertice.setVisit as false or 0 initially. I defined some getters and setters for this, but getting some type error. Code is as per below:
//Vector:
std::vector<project3::Vertex<VertexType, EdgeType>*> Vertice1;
//Class containing methods:
template <class VertexType, class ... | In C++, this is a pointer-type. Try this->mark or (*this).mark
EDIT: As Richard pointed out below, also be sure to name your parameters which you are trying to assign. In context, this->mark = mark is the same thing as this->mark = this->mark. Unless mark is a parameter, this is really unnecessary in this case. So real... |
5,616,082 | 5,616,130 | How is IXRTextBlockPtr used? | How is IXRTextBlockPtr used?
I have a XAML file that is made by Expression Blend. But the Silverlight project that corresponds to it has to be in C++ instead of C# (it has something to do with being part of an embedded system).
The automatically gernerated C++ code referrs to the TextBlock code in the header file lik... | The formal MSDN documentation for IXRTextBlock tells you exactly what to do: look at the XRPtr<> smart-pointer for IXRTextBlockPtr's interface.
If we then look at the XRPtr<> class template, we see it has operator= and Attach(). Presumably operator= will suit your needs.
|
5,616,216 | 5,616,470 | Need help in reading JPEG file using libjpeg | I followed the example code in the libjpeg example file, however I was not able to read the image data.
I have the following struct, and I created an instance of this struct.
struct ImageData {
unsigned char *pixels;
long width;
long height;
};
ImageData *imageData;
Below is my rea... | jpeg_read_scanlines function receives an array of pointers (not the direct pointer of pixels as imageData->pixels). So we should create a JSAMPARRAY first:
int buffer_height = 1;
JSAMPARRAY buffer = (JSAMPARRAY)malloc(sizeof(JSAMPROW) * buffer_height);
buffer[0] = (JSAMPROW)malloc(sizeof(JSAMPLE) * row_stride);
In you... |
5,616,386 | 5,616,431 | Is it possible to use GTK+ with C++? | I am choosing a GUI toolkit for C++ to learn. I have done some searching online and most people suggest GTKmm for C++ over GTK+. Despite that fact, I have seen some C++ applications made using GTK+.
Therefore, I just want to know the specific reasons for this:
1. Why GTKmm is preferred for C++?
2. What are the lim... |
gtkmm allows you to write code using normal C++ techniques such as encapsulation, derivation, and polymorphism. As a C++ programmer you probably already realize that this leads to clearer and better organised code.
gtkmm is more type-safe, so the compiler can detect errors that would only be detected at run time when ... |
5,616,421 | 5,616,434 | increment map<string, int> using ++ operator | I have a map to count the occurrence of words in a file.
I am reading words from the file, and each time I read a word I want to do this:
map[word]++; //(where map is the name of my map, I'm not using map as a name of course)
so that if the my map already has 'word' as a key, it increments it, otherwise it creates the... |
will my program crash because the int in my map is unitialized?
No; if the element with key word doesn't exist, the element will be created and value initialized. A value-initialized int has a value of 0.
|
5,616,464 | 5,616,488 | Why always specify iterators in std::for_each? | As far as I can tell, the idiom for iterating over STL collections looks something like this:
int a[] = { 1,2,3 };
std::vector<int> v(a, a+3);
std::for_each(a.begin(), a.end(), some_function);
Specifying the first and last iterators is useful if I want to only work on a certain range of the collection, or do somethin... | I'm totally ga-ga for STL, absolutely. But I can't recall actually ever using for_each.
The idiom is
for ( container::iterator it = coll.begin(); it != coll.end(); ++ it )
C++11 introduces sugar to reduce this to
for ( auto elem : coll )
This is similar to your convenience function, but uses free (non-member) std::be... |
5,616,603 | 5,616,638 | C++ Vector string for-loop push_back error | I feel like this is a no-brainer, but for some reason I can't understand what's happening.
When I run this part of my code, which is combining a URL with string elements from an array and then pushing that into a string vector, it pushes the first URL successfully, but then has some sort of memory leak afterwards? The ... | There are 7 items in the array indexed 0 1 2 3 4 5 6. Your loop will also include the case where i = 7 which is out of the bounds of the array.
Another issue is that you declare the vector inside of the loop, which means that every time the loop continues a new vector is created. You should declare it before the loop.
... |
5,616,821 | 5,771,054 | Retrieving client area coordinates of a character position from text control | I am in need of writing a function which can get screen coordinates from the character position in a text edit control. I am using text edit control provided by wxWidgets framework. The wxTextCtrl is not exposing any API functions which can provide this information. On Windows, I can get the information by sending EM_P... | Well, it is possible, but you need to implement a wxTextCtrl derived control that relies on underlaying platform capabilities for any particular wxWidgets port (wxMSW, wxGTK, etc).
So, because you have asked about Linux implementation. Let me explain how to implement it for wxGTK 2.9. Below is the wxTextCtrlExt control... |
5,616,930 | 5,616,957 | Which one is faster post increment or pre-increment? |
Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?
Hi,
I was asked someday ago that which one is faster variable++ or ++variable? I was little confuse. Can someone tell me which one is faster and why??
| There are few answers out there:
http://www.geekinterview.com/question_details/14424
http://www.digitalpeer.com/id/where
but this question is a duplicate
Preincrement faster than postincrement in C++ - true? If yes, why is it?
---andrew
|
5,617,043 | 5,617,327 | Why pure virtual mechanism doesn't consider inherited functions? | Before asking, I had refer to this older question. But I have still queries.
struct B1 {
virtual void fun () = 0;
};
struct B2 {
void fun () { cout<<"B2::fun()\n"; }
void fun (int i) {}
};
struct D : B1, B2 {
using B2::fun; // This line doesn't help
};
int main ()
{
B1 *pB1 = new D; // Error: cannot alloca... |
Which function is used for using keyword, B2::fun() or B2::fun(int) ? (there is no
ambiguity for
that line )
From ISO/IEC 14882:2003(E) 7.3.3.12
When a using-declaration brings names from a base class into a derived class scope, member functions in the derived class override and/or hide member functions wi... |
5,617,231 | 5,617,310 | Declaring StringStream in QT Problem | I am having problem in declaring StringStream in QT.
Here is my code:
std::stringstream ss;
for (int i = 0; i <= path.length()-1; ++i)
{
if (path[i] == '\\')
{
ss << "\\\\";
}
else... | Mixing QString and std::string or related is not generally a good idea. You should implement that with QString methods like replace( QChar ch, const QString & after, Qt::CaseSensitivity cs = Qt::CaseSensitive).
path.replace('\\', "\\\\");
BTW, you can't use QString directly with any of the standard std streams, there ... |
5,617,241 | 5,708,188 | Confused by BEGIN_MSG_MAP and BEGIN_MSG_MAP_EX | I am tracing a bug and I suspect the root could be in the use of WTL macros. When sould I use *_EX and when normal macros. For BEGIN_MSG_MAP_EX there is a note in atlcrack.h
// Note about message maps with cracked handlers:
// For ATL 3.0, a message map using cracked handlers MUST use BEGIN_MSG_MAP_EX.
// For ATL 7.0 o... | I recommend BEGIN_MSG_MAP_EX because it supports more handlers. It also supports the BEGIN_MSG_MAP handlers.
|
5,617,250 | 5,617,287 | 'GL_CLAMP_TO_EDGE' was not declared in this scope | How do I fix this? I've got both gl/gl.h, and gl/glu.h included, so what gives?
| "It''s part of OpenGL 1.2, which is why it isn''t in Microsoft''s OpenGL 1.1 header.
Add this line to your code somewhere. BTW, you should probably check the GL version at runtime before using it.
#define GL_CLAMP_TO_EDGE 0x812F
"
I just googled it and found this. Does it help?
|
5,617,251 | 5,617,464 | Offset of pointer to member | template<class T, typename U> ptrdiff_t foo(T U::* m)
{
// return offset
}
How I can get the offset of the field 'm' in this context? I would prefer to use am compile-time expression.
Thanks in advance for any help. Best regards
| Sounds like you're looking for the offsetof() macro.
|
5,617,254 | 5,617,505 | Can anyone explain this paragraph of the current C++0x standard draft? | Can anyone explain this statement from ISO N3242 §3.2, 2nd point
A member of a set of candidate functions is odr-used if it is selected by
overload resolution when referred to from a potentiallyevaluated expression.
[ Note: This covers calls to named functions (5.2.2), operator overloading
(Clause 13),user-defi... | The terminology "overloaded function" is (slightly) ambiguous between referring to the member or to the set. C++11 clarifies that functions that are never selected from a potentially-evaluated expression are not odr-used.
The term "odr-used" is new with C++11. It essentially means that the given object might be represe... |
5,617,303 | 5,617,326 | C++: Return pointer to template subclass | What is the syntax for doing something like this? When I try to compile the code below it tells me that a ';' was expected before '*', pointing to the return type of the function, ResourceManager<T>::ResourceWrapper*.
template<class T>
class ResourceManager
{
private:
struct ResourceWrapper;
ResourceWrapper*... | You are missing the typename keyword. See this question for more details on why typename is required. This code should compile:
template<class T>
class ResourceManager
{
private:
struct ResourceWrapper;
ResourceWrapper* pushNewResource(const std::string& file);
};
// (Definition of ResourceWrapper not shown.... |
5,617,497 | 5,617,629 | How to get the shortest palindrome of a string | For example :
String is : abcd
shortest palindrome is abcdcba is the solution
longer palindrome can be : abcddcba
another example:
String : aaaab
shortest palindrome is aaaabaaaa
longer palindrome can be aaaaabbaaaa
Restrictions : you can only add characters in the end.
| Just append the reverse of initial substrings of the string, from shortest to longest, to the string until you have a palindrome. e.g., for "acbab", try appending "a" which yields "acbaba", which is not a palindrome, then try appending "ac" reversed, yielding "acbabca" which is a palindrome.
Update: Note that you don't... |
5,617,636 | 5,617,928 | When std::cout is called what external API is used? (Windows) | This is a reverse engineering question.
On Windows 7 with a binary compiled using Microsoft Visual C++ 2008, when std::cout is called. Internally, what API is used to write the data? WriteFile, fwrite, ConsoleOut? I am aiming to set a breakpoint on std::cout where no source or debugging symbols are available.
| I believe it'll end up using WriteFile. It you compile a simple hello world:
#include <iostream>
int main(int argc, char **argv)
{
std::cout << "Hello" << std::endl;
return (0);
}
...and then do dumpbin /imports hello.exe, you get a list of the external functions it uses, you'll find that it imports both WriteFile... |
5,617,728 | 5,620,624 | C++ Set MIL Question | I am trying to initialize a set with more than one member in my member initialization list and I am not sure about the syntax. The ** is where I am getting my syntax error (without the ** of course). Thanks. Here is an example:
//=============================================================================
class myClas... | If you can use the Boost Assign library, the thing you ask for is easy:
#include <boost/assign/list_of.hpp>
...
mCapabilities(boost::assign::list_of(1)(2))
...
I've just tested it on MSVC8 and it works fine.
|
5,617,964 | 5,621,023 | How can I convert a wchar_t* to char* without losing data? | I'm using a Japanese string as a wchar_t, and I need to convert it to a char*. Is there any method or function to convert wchar_t* to char* without losing data?
| It is not enough to say "I have a string as wchar_t". You must also know what encoding the characters of the string are in. This is probably UTF-16, but you need to know definitely.
It is also not enough to say "I want to convert to char". Again, you must make a decision on what encoding the characters will be represen... |
5,618,083 | 5,618,139 | C++ templates: Returning list::iterator | How can I make the following code work? During compilation I get an error telling me that the searchForResource function has no return type.
template<class T>
class ResourceManager
{
private:
struct ResourceWrapper;
std::list<ResourceWrapper*> resources_; // This compiles fine
std::list<ResourceWrapper*>... | std::list<ResourceWrapper*>::iterator is hard for the compiler to understand. Prefix it with typename in both the implementation and the declaration to let the compiler know that it's a type.
Like so:
typename std::list<ResourceWrapper*>::iterator searchForResource(const std::string& file);
|
5,618,242 | 5,618,573 | Sun Studio 10 has strange `sun` constant? | Strangely, the following C++ program compiles on Sun Studio 10 without producing a warning for an undefined variable:
int main()
{
return sun;
}
The value of sun seems to be 1. Where does this variable come from and what is it for?
| It's almost certainly a predefined macro. Formally, the C and
C++ standards reserve names starting with an underscore and
a capital letter, or containing two underscores, for this, but
practically, compilers had such symbols defined before the
standard, and continue to support them, at least in their
non-compliant mod... |
5,618,250 | 5,618,374 | Qt - Horizontal spacer | I want to ask about the horizontal spacer in Qt.
I couldn't get its effect when adding it to the form for example through the Qt designer.
Why do we use the horizontal spacer? What is its purpose?
Thanks.
| It's used to prevent widgets from stretching or moving across the window.
Suppose you have a window a with a horizontal layout and the following widgets besides each other:
[LABEL EDIT]
If you resize the window, the widgets will be stretched with the window. In this case, the edit widget will probably be stretched, a... |
5,618,272 | 5,618,347 | Qt - Setting the buddies | In QtDesigner, what is the purpose of Edit Buddies? When should we enter such mode?
| If you mean this, it is for linking labels to their corresponding input controls.
|
5,618,547 | 5,618,598 | WaitForSingleObject gives Invalid Handle | h=CreateFile("c:\\test.txt",GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_READONLY|FILE_FLAG_OVERLAPPED,NULL);
OVERLAPPED ol2;
memset(&ol2,0,sizeof(OVERLAPPED));
ol2.hEvent=CreateEvent(NULL,false,false,NULL);
if(!ReadFile(h,iobuffer+pointsize,value,NULL,&ol2))
printf("Last Error %u",... | I think it should be written:
if(WaitForSingleObject(ol2.hEvent,INFINITE)!=0){
printf("Last Error %u \n",GetLastError());
Note the removed & before ol2.hEvent
|
5,618,613 | 5,620,653 | Hybrid Application with Python GUI with C++ background modules | I want to write a hybrid application which uses python as GUI component, and C++ module as background services.
I know how to program with Python, and C++, but I don't find a mature/nice way to make them work together smoothly. Could you guys shed some light on this for me? A good document/tutorial is also very apprec... | I like to use cython for writing glue code between those two worlds, or if I want stronger separation for any reason I like the ctypes approach.
|
5,618,736 | 5,618,779 | C++, MingW, ctime, nanosleep() not found? | I just wanted to use nanosleep() but it seems not to be available in MingW ctime:
#include <ctime> //this is what I need, isn't it?
How can I use nanosleep on MingW? Thanks.
| Unfortunately, MinGW doesn't provide nanosleep().
MinGW only provides functions on this list, which are in the Microsoft API.
|
5,619,015 | 5,619,252 | When a C++ program terminates on Windows what is the last function called by the termination stub? | This question is about reverse engineering and the Microsoft Standard C Library.
When a C program terimates gracefully, i.e. does a return 0; at the end of main(). What all happens (generalize please). Specifically, what is the last function called by the C library?
| You can find the sources of the Microsoft CRT in "%Program Files%\Microsoft Visual Studio x.0\VC\crt\src".
The entrypoint for executables (mainCRTStartup) is in crt0.c, or, in case the runtime DLL is used, in crtexe.c. You can see that after calling main() it calls exit(). The source code of exit() is in crt0dat.c. It... |
5,619,111 | 5,621,452 | "convert" matlab to c++ -- numerical pde's -- | i want to solve a pde according to this matlab code (part of it):
.............
% Evaluate the initial conditions
x = xl : dx : xr; % generate the grid point
% f(1:J+1) since array index starts from 1
f = sin(pi*x) + sin(2*pi*x);
% store the solution at all grid points for all time steps
u = zeros(J+1,N... | You have several serious problems here:
You have problems with all for lops. You always takes one value more than exist in arrays. Since you start your loops with zero you should use < instead of <=.
You use invalid indices in arrays: u[J][Nt-1] instead of u[i][j] in the initialization loop, and u[J][n] instead of u[J... |
5,619,292 | 5,623,566 | C++: Is default copy constructor affected by presence of other constructors and destructor? | As we know, if any constructor is declared (copy constructor included), default constructor (the one that takes no arguments) is not implicitly created. Does the same happen with a default copy constructor (the one that performs shallow copy of an object)? Also, does the presence of destructor affect this anyhow?
| The answers here are correct but not complete. They are correct for C++98 and C++03. In C++11 you will not get a copy constructor if you have declared a move constructor or move assignment operator. Furthermore if you have declared a copy assignment operator or a destructor, the implicit generation of the copy cons... |
5,619,448 | 5,619,524 | How to get the bounding rectangle after rotate at a its conner from P1 to P1'? | Please following the below image:
I want to transform a Rectangle with anchor point is center of its from P1 to P1' point.
I want to compute the bounding rectangle after rotate.
I use a solution is get new 4points: P1 => P1' and P2 => P2' etc...
But problems is: the rectangle ( I expect to get) is larger.
Please tell ... | left = min (Pi'.X for 1<=i<=4)
bottom = min (Pi'.Y for 1<=i<=4)
right = max (Pi'.X for 1<=i<=4)
top = max (Pi'.Y for 1<=i<=4)
width = top - bottom
height = right - left
bounding_rectangle = [left, bottom, width, height]
Update:
To rotate point p around center by angle radians:
v.x = p.x - center.x
v.y = p.y - center.y... |
5,619,595 | 5,619,713 | How do I call a function in a different namespace? | I have a function called testin namespace buzz.
From this test function i am calling another function called dummy which is inside namespace example.
I get the following error:
Dummy is not a member of example.
Can you please tell me how to communicate between 2 different namespaces?
Thanks
| Following code works with gcc (as expected). Your problem must be with something that is not in the question.
#include <iostream>
namespace example
{
void dummy() { std::cout << "Dummy\n"; }
}
namespace buzz
{
void test() { example::dummy(); }
}
int main()
{
buzz::test();
}
|
5,619,762 | 5,620,645 | advice on boost spirit | I'm wondering how good is the Boost Spirit Library.
I have begun to read the documentation, but it seems to be a very huge framework, and ask for a lot of time to be master. I really don't want to waste my time on a framework which is not so wonderful as it could be.
I would like to have some opinions on this framework... | My opinion is surely biased, so please take it with a grain of salt.
Spirit is a huge framework allowing to create very fast parsers and generators with C++. The created parsers and generators integrate nicely with your own data structures. Spirit requires some understanding of its underpinnings to be used efficiently.... |
5,619,794 | 5,619,812 | In C++, is a struct also a class? |
Possible Duplicate:
C/C++ Struct vs Class
I know the technical differences between a struct and a class; and of course that question has been asked before.
Object-oriented programming relates objects and classes. In C++ taxonomy, is a struct also a class?
| Taxonomically, yes. Other than their different default access specifiers, they are exactly the same in C++.
All members and attributes of a
struct are public by default.
All members and attributes of a
class are private by default.
|
5,619,810 | 5,620,499 | libjpeg decoding to BGR | I am using libjpeg to decode a jpeg image from disk to a memory buffer allocated on the heap. I use jpeg_read_scanlines to read and decode each scanline from the file. This is working perfectly, decoding each pixel as a 24-bit RGB value.
The problem is that I am using an additional third-party library which requires a ... | Several solutions for you:
Do the transformation as suggested. If you work on groups of 4 pixels, you can do everything with three 32-bit reads and writes, bitmasks and shifts, and be very fast.
Modify libjpeg's YUV to RGB transformation or the stage just after so that it swaps R and B.
Use libjpeg-turbo. It is backwa... |
5,619,857 | 5,619,977 | Why do I get an error when calling front() on boost::ptr_list? | I have got a virtual class basic_action. Class sippeers inherits class basic_action. To store instances of sippeers classes I'm using boost::ptr_list. Here's code example:
boost::ptr_list<basic_action> ActionsList;
sippeers spclass;
ActionsList.push_back(&spclass);
basic_action *sp = ActionsList.front();
Here I create... | boost::ptr_list::front() returns a reference to the templated type, not a pointer.
So in this case it's returning a basic_action&.
See the documentation here for ptr_sequence_adapter, from which ptr_list is derived.
So your code should read:
boost::ptr_list<basic_action> ActionsList;
sippeers spclass;
ActionsList.pu... |
5,619,938 | 5,619,970 | C++ global variable lifespan | I have a global variable which is an instance of a class. This class created an image in its constructor (directX).
The problem is that I am getting an access violation at runtime but the code compiles. I think the problem is that the class constructor is being called before the initialisation done in the winmain func... | You probably want to look at something like the singleton pattern if you really want to have one instance of a global, that can be initialized after the initialisation is done (essentially, the image would be constructed the first time you referenced it after which you'd use the pre-constructed version).
Globals are co... |
5,620,008 | 5,620,326 | Can anyone explain this paragraph of the current C++0x standard draft? | Can anyone explain this statement from ISO N3242 §3.2, 2nd point
A non-placement allocation or
deallocation function for a class is
odr-used by the definition of a
constructor of that class. A
non-placement deallocation function
for a class is odr-usedby the
definition of the destructor of that
class, ... | The rationale for this addition, with examples can be found here. In short, it is a clarification of exactly when an allocation/deallocation function for a class needs to be defined.
The (C++03) One Definition Rule requires that every variable or function that is used in the program, for a very specific definition of ... |
5,620,071 | 5,620,107 | How do I call overloaded member function with cv-qualifier? | I have been reading through the C++ standard and from there I found out that the cv-qualifiers are part of the function signature for member functions.
Consider the case below:
/******************************
* Function signature testing
*******************************/
class Signature
{
public:
void vSignature(... |
Is there any other way to call the vSignature() const overload aside from the above?
Yes. You can do this:
//first
const Signature s;
s.vSignature(); //calls const function
//second
Signature s;
static_cast<const Signature &>(s).vSignature(); //calls const function
//third
void f(const Signature &s)
{
s.... |
5,620,163 | 5,620,311 | use of srand() in c++ | I am new to c++ so this doubt might look basic but I am not getting the difference between rand() and srand() and what do u mean by "seed" in srand()?
when I write srand(time(NULL)), what does it do to generate random numbers, what does time(NULL) do here? and what is it?
Thanks in advance
| A random number generator requires a number(it is called seed) to generate random numbers . If the random number generator is given the same seed then every time it will generate the same sequence of random numbers . For example :-
If you run the program and it is generating random sequence 2,78,45,60 .
If second time ... |
5,620,232 | 5,620,310 | C++/CLi - Using streamwriter to write to text file is overwriting what's already there | The code I'm using to write a string to a file is as follows:
void addToWhitelist(System::String ^emailAddress)
{
StreamWriter ^pwriter = gcnew StreamWriter("whitelist.txt");
pwriter->WriteLine(emailAddress);
pwriter->Close();
}
This works well, but as soon as I run the function again, the string that was written to t... | Try adding "true" as second parameter to StreamWriter constructor.
(Boolean value says whether to append)
|
5,620,256 | 5,620,336 | Understanding how to correctly treat c++ class constants | Consider the following:
namespace MyNamespace{
class MyClass {
public:
// Public area
private:
// Private area
protected:
// Protected area
}; /* Class */
} /* Namespace */
And consider that I would like to define a constant which is specific for my class.
I usually do the following:
namespace MyNamespace{
//... | If you want the constants specific to the class and also want them to be useful somewhere else as you said, possibly outside the class, then define them as static member data in the public section of the class:
//.h file
class MyClass
{
public:
//constants declarations
static const int MYINT;
static const st... |
5,620,259 | 5,620,672 | Octave plot from Qt C++ application | I have a QT C++ application that runs the Octave program using QProcess. I am able to communicate with it by reading the standard output/error and writing to it's standard input using write method (for example: octave->write("5 + 5\n");).
As I told you I get response from octave (from the above example I get "ans = 10... | Octave, like Matlab, can be run in batch mode to perform computations without graphical UI. I assume that Octave detects that it is not run from an interactive session, and therefore automatically goes into batch mode. You would expect Octave to suppress graphical output (e.g. gnuplot output) when being in batch mode.
... |
5,620,329 | 5,620,368 | Convert std::string to char * alternative | I have done a search in google and been told this is impossible as I can only get a static char * from a string, so I am looking for an alternative.
Here is the situation:
I have a .txt file that contains a list of other .txt files and some numbers, this is done so the program can be added to without recompilation. I u... | You can get a const char* to the string using c_str:
std::string str = "foo bar" ;
const char *ptr = str.c_str() ;
If you need just a char* you have to make a copy, e.g. doing:
char *cpy = new char[str.size()+1] ;
strcpy(cpy, str.c_str());
|
5,620,494 | 5,620,529 | why a compiler can't find a template definition in .cpp |
Possible Duplicate:
Why can templates only be implemented in the header file?
I'm wondering, why a c++ compiler is not able to instanciate a template class if it is defined in a .cpp file ?
EDIT: I am sorry but I have done a search before but answer to this apparently same question are "a compiler can't find a templ... | The C++ FAQ says it all:
A template is not a class or a function. A template is a "pattern" that the compiler uses to generate a family of classes or functions.
In order for the compiler to generate the code, it must see both the template definition (not just declaration) and the specific types/whatever used to "fill ... |
5,620,656 | 5,621,661 | How does overlapped/asynchronous I/O work | Supposed I have something like this
readFile(.....&ol) //with overlapped
while(1){
////////.....
waitforsingleobject(//ol.hevent);
////
readfile(.....&ol)
}
I noticed that both readfiles read from the beginning of the file...why? In a normal readfile without overlapped/asynchronization the second readfile would... | When using overlapped I/O on a file, you pass a pointer to an OVERLAPPED object, in this case ol.
The OVERLAPPED struct has two variables, Offset and OffsetHigh. These two variables are combined into a 64-bit integer, with Offset being the lower-order DWORD and OffsetHigh being the high-order DWORD, and used as the off... |
5,620,773 | 5,932,103 | dispatch_apply with local variable declaration doesn't compile in C++ method implementation | The code
class XXX
{
vector<Record> getAll()
{
dispatch_apply(3, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t i) {
for (int j = 0; j < ...; ++j)
{ ... }
});
}
}
doesn't compile, saying "'int XXX::j' is not a static member of 'class". The doc on blocks sa... | Your code is correct, and clang will compile it. In general clang's C++ blocks support is a lot better then gcc's, and you want to use it if you can. If you need to use gcc there is a workaround, use ::j to refer to j. However that is illegal C++ and clang will choke on it, so you might want to make it conditiona... |
5,620,831 | 5,620,901 | WideCharToMultiByte() vs. wcstombs() | What is the difference between WideCharToMultiByte() and wcstombs()
When to use which one?
| In a nutshell: the WideCharToMultiByte function exposes the encodings/code pages used for the conversion in the parameter list, while wcstombs does not. This is a major PITA, as the standard does not define what encoding is to be used to produce the wchar_t, while you as a developer certainly need to know what encodin... |
5,620,862 | 5,620,911 | operator overloading in c++ |
Possible Duplicate:
Operator overloading
Hi guys can some one please suggest a good tutorial on operator overloading?
I was going through this code on operator overloading and I have the following doubts
code:
#include <iostream>
using namespace std;
class Array {
int *a;
int size;
int capacity;
public:
Ar... |
Google is your friend :) or have a look at http://www.parashift.com/c++-faq-lite/operator-overloading.html
It overloads the << operator
It overloads the [] operator, so you can use yourobject[something]. It's used e.g. by std::map
It looks like the beginning of the implementation of an overloaded operator.
It's a refe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.