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,460,186 | 5,460,699 | Preventing header explosion in C++ (or C++0x) | Lets say with have generic code like the following:
y.hpp:
#ifndef Y_HPP
#define Y_HPP
// LOTS OF FILES INCLUDED
template <class T>
class Y
{
public:
T z;
// LOTS OF STUFF HERE
};
#endif
Now, we want to be able to use a Y in a class (say X) we create. However, we don't want users of X to have to include the Y ... | You can use either unique_ptr or shared_ptr to handle the incomplete type. If you use shared_ptr, you must outline ~X() as you have done. If you use unique_ptr you must outline both ~X() and X() (or whatever constructor you're using to construct X). It is the implicitly generated default ctor of X that is demanding ... |
5,460,270 | 5,461,785 | Quickly enter command-line parameters for Visual Studio debugging? | I want to change my command-line arguments and then debug my executable.
With the default Visual Studio UI, this takes me several tortuous mouse and keyboard actions:
Project ... right click ... Configuration Properties ... Debugging ... Command Arguments ... type args ... ENTER ... F5
Is there a way to make this com... | Macro below should help. Open "Tools->Macros->Macro Explorer", then create new module, edit it, and copy-paste code below. Required command is SetCommandArgsProperty. UI is not nice, but it works (VS 2005, I hope this will also work in VS 2010). Then add any shortcut you like to run this macro.
Here are some details:
... |
5,460,371 | 5,460,401 | Is it ok to cast a STL container with Base type to Derived type? | Is it ok to cast a STL container from Base type to Derived type ?
For example, I have two vectors. First one is in type of a Base class, second is in type of a Derive class.
class Base
{
// Code
};
class Derive : public Base
{
// Code
};
Usage
vector<Base*>* vec_base = new vector<Base*>;
// Add some Deriv... | This is definitely not ok, and is one of the examples of c-style casts masking errors. "It works for me" is not indicative of well defined behaviour in this instance.
If you really want to do this I'd suggest:
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
class Base
{
// Code
virtual... |
5,460,482 | 5,462,637 | dlsym()'ing a global variable in C++ | I want to make a program which is able to dlopen() a series of libraries (written by myself) and run all the functions stored in a global variable called test_suite inside that .so file, which is a NULL-terminated array of function pointers (the functions' signatures are predefined by myself, no need to worry about tha... | The problem isn't one of name mangling. (Or probably isn't: public
variable names are not usually mangled.) The real problem is that the
"const" means implicit static, rendering the variable invisible outside
the translation unit. To avoid this, the variable must be explicitly
declared extern. And "The form of link... |
5,460,536 | 5,460,895 | glutBitmapString access violation | (OS: Windows 7, Compiler: Visual Studio 2010 C++ compiler)
I've got a correctly working OpenGL program that draws some spheres and models, applies some shaders etc.. etc..
Now I thought it would be nice to add some text, so I added the following three lines to my draw method:
glColor3f(0.5f, 0.5f, 0.5f);
glRasterPos2f(... | glutBitmapString is of type const unsigned char* and not of unsigned char*. Would that help? I had problems with string casting as well.
And I found out, that I wasn't closing my string, because the unsigned char* should be 1 longer than a string. Here was a snippet that solved it for another method with the same param... |
5,460,541 | 5,462,435 | Is the C++ Standard Library part of the C++ Language? | Is the C++ Standard Library part of the C++ Language? (note "language", not "standard"; both are, of course, part of the standard).
If so, why? If not, why not?
The answer to this question may differ across C++98, C++03 and C++0x.
It's not subjective because it can be inferred from wording/requirements in the relevant ... | The very first words in all of the versions of the standard I've seen
are "This International Standard specifies requirements for
implementations of the C++ programming language." In other words,
anything specified in the standard is part of the "language".
In other places, the standard does distinguish between the li... |
5,460,554 | 5,460,658 | JNI - problem with threads and jobject | I have called a native program which creates another thread, which attaches itself to the JVM. Now I want to access the methods of the JVM, but it fails. Here is the code:
//
// This is the native function that gets called first.
// it creates another thread which runs, and also calls the printing-methods in my
// jav... | m_job = job;
This just keeps the local reference which is invalid as soon as you return to java. You need to make a global referene with NewGlobalRef and store that.
JNIEnv* jenv = new JNIEnv();
applet_java_jvm->AttachCurrentThread((void**)jenv,NULL);
Should be:
JNIEnv* jenv = 0:
applet_java_jvm->AttachCurrentThread(... |
5,460,562 | 5,460,857 | Why it is impossible to create an array of references in c++? | C++ Standard 8.3.2/4 says:
There shall be no references to
references, no arrays of references,
and no pointers to references.
But I can't understand why this restriction is added to c++. In my opinion the code bellow can easily be compiled and work? What is the real cause of this restriction?
int a = 10, b = 20;... | Because indexation into an array is actually defined in terms of an implicit conversion to a pointer, then pointer arithmetic. So to support this, you'd have to also support pointers to references, and define what pointer arithmetic means on them.
|
5,460,628 | 5,460,760 | Is there any good way to remove elements in the vector or deque? provide some sample code is more than welcome | For example, I good 2 vector, say vector current, vector to_delete. Is there some good way to delete elements which appear both in current.
Here is my way to do it. I guess it not looks good. So please help me out. Thank you.
#include <iostream>
#include <vector>
using namespace std;
int main(){
vector <double> cur... | You could use std::find() instead of a manual loop to find the position of the element that should be deleted.
std::vector<double>::iterator del =
std::find(current.begin(), current.end(), to_delete[i]);
if (del != current.end())
current.erase(del);
|
5,460,678 | 5,460,776 | what's the best way to delete an entry map<int, A*> | I discussed with my coworker about how to delete an entry in a map
the map has the int as the index and a pointer pointing to an object.
I said, first release the object, and then delete the entry.
My coworker said first delete the entry and then release the object.
So what's the best way? Any trick for this questi... | Unless you have a multi-threaded environment, either way would work. The rule of thumb is that, once your function returns, there should be no dangling pointers left, i.e. no pointers to the object that just was deleted.
The only problem that could occur is that if you delete the entry first, you have to make sure to h... |
5,460,746 | 5,460,774 | Is Nokia mis-using static_cast? | I've just came across this example:
Scroll down to the bottom of the page, where you will find
QWidget *pw = static_cast<QWidget *>(parent);
Parent is of type: QObject, which is the Base class of QWidget, so in this case, isnt:
dynamic_cast should be used?
such as:
QWidget *pw = dynamic_cast<QWidget*>(parent)
Thanks... | If you know that you are down-casting from a base to a descendant class (i.e., you know the object is actually an instance of the descendant class), then static_cast is perfectly legal (and more performant).
|
5,461,129 | 5,461,454 | Reversing a char array in C++ causing an error | I am using the following code in order to reverse a char array. My code as well as the error can be found below.
My code:
char * reverseStr(char* s) {
int i=0; //legnth of string
while(s[i]) i++;
char reversed[i];
for(int j=0; j<i; j++) {
reversed[j] = s[i-j - 1]; //look at this later
}
return *(reversed);
}
The ... | In your code i is not const.
char reverseStr(char* s) {
int i=0; // --->> NOT CONST
while(s[i]) i++;
char reversed[i];
for(int j=0; j<i; j++) {
reversed[j] = s[i-j - 1]; //look at this later
}
return *(reversed);
}
char reversed[i]; ---> Variable Length Array in C++?? i is supposed to be known at Compile time.
|
5,461,291 | 5,461,354 | std::vector member functions | I saw this question in a book:
What member functions of the std::vector are controlling the allocated memory ?
Can someone answer this?
Thank you
| Memory allocations of Container classes is managed by the underlying Allocator defined for each of them.
Almost All member functions will control the allocated memory.
|
5,461,357 | 5,462,423 | Hierarchical k-Means in OpenCV without knowledge of "k" | I'm trying to cluster a set of 4D vectors, without knowing how many clusters there should be in advance. In the past, I've been able to use cvKmeans2 to cluster, given knowledge of the number of clusters. I was trawling through the API and came across cv::flann::hierarchicalClustering. This looks like it will do what I... | You have to pass a reference to createIndex, i.e. createIndex(*framePoints) (note the asterix!). Another error might be createIndex being a non-static (member) function. In that case you'd have to create a KMeansIndexParams object and call createIndex on that.
|
5,461,394 | 5,462,320 | two main in visual c++ | how can I run two main Visual Studio (Visual C ++)..
I would like to have a main that represents the server and a main that is
the client and run them running on two different consoles.
how can I do?
| Create two functions:
int server_main( int argc, char* argv[] );
int client_main( int argc, char* argv[] );
in the actual
int main( int argc, char* argv[] )
check for a command line argument ( --server or --client ) and then depending on which one is present, delegate to server_main or client_main.
When it comes to d... |
5,461,761 | 5,861,561 | Project properties lost on external checkout | Our company might be moving from CVS to Subversion soon. This has brought about an issue for us, which I am trying to solve.
For CVS and Eclipse, we were able to use team project set files to gather various modules and check them out together (http://vpms.de.csc.com/projectset/). This made it very easy to manage projec... | In case anyone needs this, here's what I found:
http://vpms.de.csc.com/projectset/
&
http://www.polarion.org/index.php?page=download&project=subversive
OR
http://www.giniality.com/old/update/projectset/
for Subversion + Project Set integration.
There is no need to break your project set. Once you have the integration p... |
5,461,764 | 5,462,092 | Implicit conversion to a C++ template object | I have a class A:
template <typename T, int I> struct A {};
and a class B. I would like object's of type B to implicitly convert to A when given as function arguments. B looks like this:
template <typename T>
struct B {
operator A<T,0> &() const { return *new A<T,0>(); }
};
However, my test (below) fails with GCC 4... | If you want an implicit conversion from B to A you would need either:
A cast operator on B:
operator A<T,0>();
or an A constructor which takes a B reference:
A( const B& other );
or for B to derive from A. What you have declared:
operator A<T,0> &() const;
looks a bit like an ill-declared address-of overload.
Howeve... |
5,462,022 | 5,462,214 | tokenizing a string of data into a vector of structs? | So I have the following string of data, which is being received through a TCP winsock connection, and would like to do an advanced tokenization, into a vector of structs, where each struct represents one record.
std::string buf = "44:william:adama:commander:stuff\n33:luara:roslin:president:data\n"
struct table_t
{
... | For breaking the string up into records, I'd use istringstream, if only
because that will simplify the changes later when I want to read from
a file. For tokenizing, the most obvious solution is boost::regex, so:
std::vector<table_t> parse( std::istream& input )
{
std::vector<table_t> retval;
std::string line;... |
5,462,032 | 5,462,063 | set<class> insert problem | why is the following programm not working?
How can i fix it?
#include <iostream>
#include <set>
using namespace std;
class K {
private:
long a;
};
int main ()
{
K a;
set<K> b;
b.insert(a);
return 0;
}
| std::set requires a sorting of the elements. It requires that you can compare its elements according to some ordering.
Either add an operator < for your class K or provide the second template argument – the comparer – to the set class that determines the ordering between two K instances.
Overloading the operator < is s... |
5,462,046 | 5,463,672 | MPI_Scatter Segfaulting | I'm working on a parallel sort program to learn MPI, and I've been having problems with MPI_Scatter. Every time I attempt to run, I get the following:
reading input
Scattering input
_pmii_daemon(SIGCHLD): [NID 00012] PE 0 exit signal Segmentation fault
[NID 00012] 2011-03-28 10:12:56 Apid 23655: initiated application t... | Hah! Took me a while to see this one.
The trick is, in MPI_Scatter, the sendcount is the amount to send to each process, not in total. Same with gather; it's the amount to receive from each. That is, it's like MPI_Scatterv with counts; the count is to each process, but in this case, it's assumed to be the same.
so... |
5,462,118 | 5,865,882 | Solaris shared libraries and global variables | I have an issue with global variables in shared library on Solaris.
Consider following sample:
class Foo
{
public:
Foo() { Init(); }
private:
void Init() { // do something }
};
I have some code in shared library:
Foo g_Foo;
I've noticed that Foo constructor is never called on Solaris while the same code works L... | Are you creating the shared object with the -G flag? e.g.
CC -G -o mylib.so myfile.cpp
If you don't specify -G, then the compiler may not initialise global variables correctly. See compiler documentation here.
Note, the docs also say you can't use ld, but need to use CC to do the linking.
|
5,462,388 | 5,462,526 | Relation between constexpr and pure functions | Am I right, that:
Any function defined with constexpr is a pure function, and
Any pure function can be and must be defined with constexpr if it's not very expensive for compiler.
And if so, why arent <cmath>'s functions defined with constexpr ?
| To add to what others have said, consider the following constexpr function template:
template <typename T>
constexpr T add(T x, T y) { return x + y; }
This constexpr function template is usable in a constant expression in some cases (e.g., where T is int) but not in others (e.g., where T is a class type with an operat... |
5,462,749 | 5,462,787 | Adding large numbers in C | I am a bit confused about the behavior of c when it comes to adding large numbers. This is probably a beginner's question but would appreciate any help.
unsigned long total = 0;
total = 1124073472 + 2835349503;
total += 2533359615;
printf("Total: %u\n", total);
The total which gets printed above is not correct. The fi... | You're correct, it's because of overflow. Using a 64-bit type will fix it - you will need to change your printf() format string to printa 64-bit type too, though. Making total an unsigned long long will probably get you a 64-bit type, but the safest way would be to use one of the typedefs from stdint.h. Here's an e... |
5,462,952 | 5,468,799 | WSARecvFrom on unconnected UDP socket does not return | I am writing a small program that tests an UDP network service. The implementation of the service is allowed to create a new socket for the session and respond to the client from there, at which point the client is then required to talk to this address (similar to TFTP).
Minimal client sans error checking looks like th... | Meh, it was a firewall issue. Adding the application to the list of programs allowed to receive incoming traffic fixed the issue.
|
5,462,954 | 5,463,026 | typedef std::runtime_error MyError vs class MyError : public std::runtime_error | I'm currently implementing some custom exceptions in a project and can't decide wither to typedef my exceptions or to derived a new class for every exception. Interested in the potential pros and cons of each and if one is preferable?
| Pros in deriving your own class are simple: you can dispatch on it in catch handler.
If you decide not to implement your own class, I still doubt you need this typedef: what are you abstracting from? You may as well use plain std::runtime_error.
Also you might be interested in David Abrahams'es article about exception ... |
5,463,009 | 5,464,202 | Extension methods in c++ | I was searching for an implementation of extension methods in c++ and came upon this comp.std.c++ discussion which mentions that polymorphic_map can be used to associated methods with a class, but, the provided link seems to be dead. Does anyone know what that answer was referring to, or if there is another way to ext... | Different languages approach development in different ways. In particular C# and Java have a strong point of view with respect to OO that leads to everything is an object mindset (C# is a little more lax here). In that approach, extension methods provide a simple way of extending an existing object or interface to add ... |
5,463,034 | 5,463,044 | C++ Vectors: Why is this piece of code not working? | vector< vector< vector<int> > > myArray(5, vector< vector<int> >(4));
vector<int> testArray();
myArray[0][0].push_back(testArray);
I don't understand. I'm just trying to append a new element to it.
Edit: Second line was wrong but this still doesn't compile.
#include <iostream>
#include <vector>
using namespace std;
i... | vector<int> testArray();
Should be:
vector<int> testArray;
vector<int> testArray(); is a forward declaration of a function called testArray which returns vector<int>.
You also have one level of indirection too much:
myArray[0].push_back(testArray);
or
myArray[0][0] = testArray;
|
5,463,035 | 5,463,164 | Beginner programmer; program instantly closes on switch (C++) | I've been messing around with my very basic C++ knowledge (been programming for two days), attempting to write a program that calculates user input around phi (1.61803399).
Here's the code, apologies if its a mess:
#include <iostream>
#include <math.h>
using namespace std;
//Prototypes:
float phiExpo;
float phiNegEx... | Your program doesn't close on the switch statement when I run it; I get your second text.
There are a few problems I see though:
First, as faster people have noted, your returns quit out of the application instead of outputting the answer.
Secondly, after you change your code to cout rather than return, you will want t... |
5,463,100 | 5,464,220 | Using RegQueryValueEx and HKEY_PERFORMANCE_COUNTER to Get "Disk Bytes/sec% | I've looked for examples and documentation, but I still can't figure this out...
How do you use RegQueryValueEx (not the PdhXxx functions) to query for something like Disk Bytes/sec?
I've tried the following:
DWORD type;
static union { TCHAR Data[32 * 1024]; PERF_DATA_BLOCK Perf; } perf;//Stack buffer
DWORD cbData = si... | You can't query for the data by name like that. Instead, you need to query by index. MSDN can help you with some code to find out the appropriate index to query. Unfortunately, you need to make the determination of which index at run-time.
For example, the following SHOULD retrieve the performance data for the processo... |
5,463,229 | 5,463,362 | Unexposed private member variables vs. global variables in the source file | I am looking at some code in a company I am currently working at and I see a few (not a lot) declarations of static global variables in the *.cpp files (for example, to store a list of listeners) where the .h/.cpp files belong to a class. If a variable (static or otherwise) that is used only by class itself, I always d... | The main advantage to this way is reducing the amount of "unnecessary" stuff in the *.h file. This might slightly improve compile times and/or rebuild complexity when files or modified, and it may make the header file slightly easier to read.
(In my opinion, these advantages are small, and I will usually prefer the cl... |
5,463,325 | 5,463,336 | Unexpected results for "sizeof" of strings | Why would sizeof in the following cases print different values:
printf("%d",sizeof("ab")); //print 3
char* t="ab";
printf("%d",sizeof(t)); //print 4
In the first case I have 2 characters... Shouldn't sizeof print 2? Because they are 2 bytes?
|
Strings in C are null terminated.
"ab" in memory looks like 'a' 'b' '\0'
While t is a pointer, so size is 4.
|
5,463,408 | 5,477,622 | Visual Studio 2010 very slow, unusable | I've searched for this topic but can't seem to find posts that relate exactly to what I am experiencing.
I have a Visual Studio solution that I need to work on, its fairly large and contains 16 projects.
Everything is just so so slow and choppy (Except start-up which is actually quite fast).
Clicking a line in the text... | Thanks for all the replies.
I've switched to using visual c++ express, it's much quicker, now I can actually do some coding.
Best solution I have for now.
|
5,463,437 | 5,463,462 | Operator= overloading in C++ | In the book C++ Primer it has a code for C - style character arrays, and shows how to overload the = operator in the Article 15.3 Operator =.
String& String::operator=( const char *sobj )
{
// sobj is the null pointer,
if ( ! sobj ) {
_size = 0;
delete[] _string;
_string = 0;
}
else {
... | It supports the following idiom:
String a, b;
const char *c;
// set c to something interesting
a = b = c;
For this to work, b = c must return an appropriate object or reference to assign to a; it's actually a = (b = c) according to the C++ operator precedence rules.
If you'd return the pointer this, you'd have to wr... |
5,463,907 | 5,464,161 | CUDA: more dimensions for a block or just one? | I need to square root each element of a matrix (which is basically a vector of float values once in memory) using CUDA.
Matrix dimensions are not known 'a priori' and may vary [2-20.000].
I was wondering: I might use (as Jonathan suggested here) one block dimension like this:
int thread_id = blockDim.x * block_id + thr... | The dimensions only exist for convenience, internally everything is linear, so there would be no advantage in terms of efficiency either way. Avoiding the computation of the (contrived) linear index as you've shown above would seem to be a bit faster, but there wouldn't be any difference in how the threads coalesce.
|
5,463,960 | 5,464,180 | Can I have an array of integers for one constructor and a single integer for the other constructor? | Are the following constructors allowed in the same IntList class?
IntList(int length);
IntList(int data[]);
| That's fine, but note that latter is the same as int* data, which is a pointer and not an array.
Arrays are non-copyable and must be passed by reference:
typedef int array_type[5];
IntList(const array_type& arr); // same as: IntList(const int (&arr)[5]);
You can also take an array of any size using templates:
templat... |
5,464,178 | 5,464,234 | Lightweight cross platform database engine to work with my Qt Application | I am developing a Qt application to run on Windows, Mac and Linux (Ubuntu Desktop). Development is in C++ of course and it's a desktop application that needs to store and retrieve "tabluar" information on an ongoing basis.
I do not want to bother my users with pre-installing MySQL or anything alike.
Is there a lightw... | Try SQLite : http://sqlite.org
|
5,464,397 | 5,464,436 | Why, if the c++ standard says that the syntax is incorrect, does g++ allow it? | I just read a comment that said something along the likes of:
"You should never use void main() you should always use int main()."
Now I know the reasons for using int main() (so that you can check for success on return and whatnot) but I didn't know that using void main() was illegal. I did some investigating and ... | That only means that a particular version of your compiler may allow it, but the later versions (which is likely to be more Standard conformant) may not allow it. So better write Standard Conformant code from the beginning!
|
5,464,496 | 5,464,644 | Passing a Functor as a param to a method | I have the following two classes that exhibit the Command pattern. (Unfortunately, both have a unique method name.)
//pseudocode
class Subscriber {
virtual void receive(const Event&) = 0;
}
class Dispatcher {
virtual void dispatch(const Event&) = 0;
}
I have a class template that has a list of some type wit... | This may be the most straight-forward way:
class event_forwarder // make private in Registry
{
public:
event_forwarder(const Event& event) :
mEvent(event)
{}
void operator()(Subscriber& subcriber) const
{
subscriber.receive(mEvent);
}
void operator()(Dispatcher& dispatcher) const
... |
5,464,858 | 5,468,786 | Setting up 64 bit variables in C++ | I'm wondering how to set a 64-bit variable in C++ for my testbench. When I use the variable_name.io_int_write(0,value0) and variable_name.io_int_write(1,value1) (for the lower & upper bits) I can see the variables are set but in the reverse manner.
Ex: When I want it to be 000...002, I see 200...000
Is there an alterna... | If you want to set a 64bit integer variable to a constant value, you can simply say something like:
long long var64bit = 1L;
The L at the end of 1L says that it is a 64bit constant value of 1.
If you are comfortable with hexadecimal and want a 64bit bit-field constant, then the usual way of setting a 64bit variable wo... |
5,464,980 | 5,465,017 | Access derived class' functions through pointer (C++) | Here's an example of the situation:
CAnimal *poTest = new CDog();
When I write "poTest->" All I can see are functions from the base class (in example: CAnimal) and not the ones in the derived one. How can I access these?
| You've declared poTest as a CAnimal.
So it makes sense that you'll only see what a CAnimal can see.
If you want to use methods that a CDog uses, declare it so.
|
5,465,227 | 5,465,278 | recursion problem in parsing with RapidXML/C++ class pointers side-effect | I want to share this odd but interesting situation I stumbled upon recently while trying to use RapidXML for XML parsing in C++.
I wanted to write a recursive function to search and return a particular node among the children of a given node. My first try was:
xml_node<>* get_child(xml_node<> *inputNode, string sNodeFi... | When you find a child by recursing, return it. If you don't find a child, return 0
xml_node<>* get_child(xml_node<> *inputNode, string sNodeFilter)
{
// cycles every child
for (xml_node<> *nodeChild = inputNode->first_node(); nodeChild; nodeChild = nodeChild->next_sibling())
{
if (nodeChild->name() ... |
5,465,293 | 5,465,371 | Function Overloading Based on Value vs. Const Reference | Does declaring something like the following
void foo(int x) { std::cout << "foo(int)" << std::endl; }
void foo(const int &x) { std::cout << "foo(const int &)" << std::endl; }
ever make sense? How would the caller be able to differentiate between them? I've tried
foo(9); // Compiler complains ambiguou... | The intent seems to be to differenciate between invocations with temporaries (i.e. 9) and 'regular' argument passing. The first case may allow the function implementation to employ optimizations since it is clear that the arguments will be disposed afterwards (which is absolutely senseless for integer literals, but may... |
5,465,537 | 5,466,809 | QListWidget send doubleClicked signal with no items | I have a QListWidget on a dialog that I want to do something (for example, open a QFileDialog window) when a user double-clicks on the QListWidget. Unfortunately, the void doubleClicked (const QModelIndex & index) only fires when there are items in the list.
Is it possible to get the widget to fire the signal whenever ... | You can install an event filter to the listwidget's viewport widget, something like this:
listWidget->viewport()->installEventFilter(this); // "this" could be your window object.
In the eventFilter method check for the QEvent::MouseButtonDblClick event:
bool YourWindowClass::eventFilter(QObject *obj, QEvent *event)
{
... |
5,465,647 | 5,465,799 | Qt how to capture event indicating that all gui elements are ready | I'm wondering if it is possible to capture an event that is generated when all
Qt objects are initialized and ready ?
It seems that some things can't be done in window's constructor. And they work fine in slot implementation.
For example, when I want to access root window of my application I do it like that
// in *.h
... | You can use a single-shot timer for this. In your main window class, define a slot function called say, appReady(). In the constructor, create and connect a single shot timer using QTimer::singleShot(0, this, SLOT(appReady())); This timer should fire as soon as the event loop is up and running and there are no more sta... |
5,465,730 | 5,467,163 | Concern over handling bad call to accept() | I'm writing a MUD server for personal learning purposes and I've, happily, managed to wrap up the socket stuff up into a couple of classes and everything appears to be working correctly; the server listens for and accepts connections and currently takes text from the client and sends it right back.
The thing is I'm not... | First: don't set the socket to 0: that's a valid fd for sockets on some *NIX systems, and a bad habit to take. Assume the only invalid socket fd is -1. Doing anything else will give you real bugs in real software later on (trust me: I'm speaking from experience debugging code that used 0 as an invalid socket fd).
Other... |
5,465,770 | 5,465,798 | templated circular inheritance | in this code, compiler complain about undefined MyClassB, which is understandable :
class MyClassA;
class MyClassB;
template <class T> class BaseClass : public T {
};
class MyClassA : public BaseClass<MyClassB> {
};
class MyClassB : public BaseClass<MyClassA> {
};
but in this code, compile is successful and no comp... | Because your implementation of std::vector allows an incomplete type. This is a side effect of the instantiation rules of member functions of class templates: they aren't instantiated until they're used. So the functions that do need it to be a complete type aren't instantiated, yet. So no errors.
Contrarily, it does n... |
5,466,391 | 5,467,259 | C, Linux, getcwd/chdir(): get binary path | I want to open a number of files (log4cxx configs, other logs etc) relative to binary's location.
Unfortunately, both getwd() and getcwd() are giving me the directory, from which I try to run binary at known path, instead of giving me the path where the binary is located (and where the data is).
How to get the app's pa... | This is exactly the kind of thing autoconf lives for, and supporting those standard directories is pretty much mandatory if you ever want anyone other than the programmers who wrote your software to use it. Once set up properly, to debug out of your home directory all you have to do is pass a different --prefix= value... |
5,466,627 | 5,466,648 | pow() returning 0 (C++) | Could someone explain why pow() in the following code is returning a 0 when the program is run, rather than the actual calculation? I'm a newbie to programming and I'm entirely stumped.
Thanks for any help.
#include <iostream>
#include <math.h>
#include <windows.h>
using namespace std;
//Prototypes:
double phiExpo;
d... | You never actuall call pow. On choice 3, you only call opt3f, which only returns the global variable phiExpo, which is initialized to 0 because it's global. Then you also need to return from the phiExpof function, like others already pointed out.
|
5,466,841 | 5,466,856 | Multiple-Line String Initialization | string menu = "\nChoose an option:\n1. Push Front\t2. Push Back\t"
+ "3. Pop Front\t4. Pop Back\n5. Front Value\t6. Back Value\t"
+ 7. Delete Nodes\n8. Clear List\t9. List Size\t10. Print List\t11. Quit\n";
I am trying to figure out how to initialize a string that is about 180 characters long, but I want to concatenat... | Remove the + signs, the preprocessor will concatenate strings like this:
string menu = "\nChoose an option:\n1. Push Front\t2. Push Back\t"
"3. Pop Front\t4. Pop Back\n5. Front Value\t6. Back Value\t"
"7. Delete Nodes\n8. Clear List\t9. List Size\t10. Print List\t11. Quit\n";
|
5,466,925 | 5,466,968 | reading a line in text file twice | I have this text sample
Ahmed 10
kmal 5
doola 6
And I am using this code to read it
if (myfile.is_open())
{
while ( myfile.good() )
{
myfile >> name;
myfile >> phone;
cout << name <<" "<<phone<<endl;
}
myfile.close();
}
I get this output
Ahmed 10
kmal 5
doola 6
doola 6
Why does this code read the la... | Try
while( myfile >> name >> phone ) {
// your code here
}
I believe the problem with the other approach is that eof isn't signaled until you actually try to read more than you should. That is, when you attempt to myfile >> name on the last round. That fails, as does myfile >> phone and only then do you break out ... |
5,467,177 | 5,467,233 | Should you write "public virtual" or "virtual public" in virtual inheritance? | Based on http://en.wikipedia.org/wiki/Virtual_inheritance
class Animal
{
...
};
// Two classes virtually inheriting Animal:
class Mammal : public virtual Animal
{
...
};
I also saw books use the following syntax,
class Mammal : virtual public Animal
{
...
};
Question> Which is one the C++ standard?
Thank you
| From ISO/IEC 14882:2003(E) - 10.1
A list of base classes can be specified in a class definition using the notation:
base-clause:
: base-specifier-list
base-specifier-list:
base-specifier
base-specifier-list , base-specifier
base-specifier:
::opt nested-name-specifieropt class-name
virtual access-... |
5,467,199 | 5,467,438 | Having multiple instance of global variables from same DLL | Currently, I have a system with the following simplified view.
The entire system run under single process
------------------------------------------
--- DLL0.DLL --- COMMON.DLL (contains global_variable in COMMON.DLL)
EXE ---|
--- DLL1.DLL --- COMMON.DLL (contains global_variable in COMMON.DLL)
The sour... | If I understand the situation correctly, COMMON.dll is the legacy code and the legacy code is used by both DLL0.dll and DLL1.dll.
Without knowing all the details I would suggest the following:
1) Create a global variable in DLL0.dll and DLL1.dll.
2) Initialize each global variable from step 1 with COMMON.dll's global... |
5,467,205 | 5,467,219 | C++ -- which constructor of string is call when we use string(0)? | Given the following code,
class A
{
public:
A() : str(0) {}
private:
string str;
};
Based on this http://www.cplusplus.com/reference/string/string/string/
string ( );
string ( const string& str );
string ( const string& str, size_t pos, size_t n = npos );
string ( const char * s, size_t n );
string ( const char * ... | This one:
string ( const char * s );
It's converted to a null pointer. (And also gives you undefined behavior, since s cannot be a null pointer.)
|
5,467,218 | 5,468,894 | Opengl: 2d HUD over 3D | I have looked at some questions posted here on the matter and still cant work out why my 2d HUD appears but makes my 3d Rendered world disappear.
EDIT: It seems that the 2d scene is taking control of the entire screen so every now and then I can see the 3d scene glitching through the 2d scene. So even though I its onl... | Took a little while to figure it out, so just in case others have the same issues:
...After Drawing 3d Stuff...
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0.0, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0, -1.0, 10.0);
glMatrixMode(GL_MODELVIEW);
//glPushMatrix(); ----Not sure if I need this... |
5,467,226 | 5,467,272 | Looking for C/C++ language and standard libraries specifications |
Possible Duplicate:
Where do I find the current C or C++ standard documents?
I have several C books, and one of them, C by Discovery, explains the language very well. But so far I don't seem to have been able to find the full C/C++ language and library standards and lists of functions, types, etc., in whole detail.
... | The Wikipedia article C99 has a link at the bottom to a draft of the C99 language specification. It is a draft because the final published version you have to pay for. But the draft is basically accurate, so it's a good reference. This is an extremely long specification of the entire language including the library, but... |
5,467,378 | 6,159,706 | Configuring "Application Verifier" In Visual Studio | I see that I can launch application verifier within Visual Studio 2008 via Debug->Start With Application Verifier. But the documentation for app verifier shows a bunch of options that can be configured if it's UI is launched separately from Visual Studio. I can't figure how to set those options from within Visual Stu... | I often use Application verifier at my workplace, with VS2005 and with Windbg, so I can tell you a bit how it works.
First, you should launch the Application Verifier standalone application in order to add your application to the list of applications instrumented by Application verifier. Then, in the 'Test' right pane ... |
5,467,406 | 5,467,412 | Maximum capacity of STL queue | What is the maximum capacity of an STL queue, considering that it holds ints. By maximum capacity I mean the max number of integers it can hold at maximum capacity.
thanks
| C++ Reference holds an answer for that.
In the end, it relies on the underlying container of std::queue. Its max_size is also the max_size of the queue.
|
5,467,414 | 5,467,431 | Writing code to help the compiler to do optimizations | Does anyone know if there is a list of what a compiler do to optimize a source code? I prefer GCC as example.
I want to know what a programmer should do with the code to get good optimization and help the compiler to optimize it. Some optimizations by programmer may avoid the compiler to do better optimizations.
Exampl... | Seriously, just leave that up to the compiler. I've seen the code that gcc outputs at its "insane" -O3 level and it's proof positive that the people who wrote those optimisation engines are either aliens or from a substantially distant future time.
I've yet to see a situation where register or inline made an appreciabl... |
5,467,576 | 5,467,874 | Different output for different compiler - C and C++ | Can you think of 'a program' which gives 'different outputs for a C and a C++ compilers' (yet gives consistent output under the same language)?
| This program produces 12 in C++ or C99, and 6 in C89:
#include <stdio.h>
int main()
{
int a = 12//**/2;
;
printf("%d\n", a);
return 0;
}
|
5,467,785 | 5,467,823 | Circular Inclusion with Templates | The following code compiles perfectly:
// MyFile.h
#ifndef MYFILE_H_INCLUDED
#define MYFILE_H_INCLUDED
template <typename Datatype>
class MyClass
{
public:
void MyMethod();
}
#include "MyFile.cpp"
#endif
// MyFile.cpp
#ifndef MYFILE_CPP_INCLUDED
#define MYFILE_CPP_INCLUDED
#include "MyFile.h"
template ... | If you include the MyFile.tpp (I renamed it from .cpp), then you don't need to include the MyFile.h. #includeing a file is like exactly copying it's content into the file where it's included. Other from that, it's a common practice to organize the headers a bit. (Though you don't need the include-guards in the MyFile.t... |
5,467,956 | 5,468,255 | C++ -- vptr & vtbl associated with object or class? | vptr -- virtual table pointer
vtbl -- virtual table
Question 1> Is it correct that vptr is associated with the object of a class?
Question 2> Is it correct that vtbl is associated with the class?
Question 3> How do they really work together?
Thank you
| Note that vptr and vtbl are Implementation defined the C++ standard does not even talk about them. However, most known compilers implement dynamic dispatch through vptr and vtbl.
Question 1: Is it correct that vptr is associated with the object of a class?
YES
vptr is associated with the object of a Class which contai... |
5,467,999 | 5,468,009 | C++ new pointer from pointer to pointer? | I have a template linkedList that I would like to dynamically create "head" pointers for...
I seem unable to get any syntax to work.. my best guess is:
linkedList<int>** ptr;
ptr = new (linkedList<int>*)[1];
But it doesn't work. I'm fairly new to C++ so any help is appreciated! Thanks!
| To get a pointer, do:
T* ptr = new T;
where T is your type.
For a pointer-to-pointer, do:
T** ptrptr = new T*;
allocating the space for one pointer, which still needs to be filled like the first method:
*ptrptr = new T;
Now you got a valid pointer-to-pointer.
|
5,468,186 | 5,468,363 | First in first out c++ algorithm | Ive been asked to write a code to calculate average waiting time and average turn around time of Cpu algorithms. FIFO, SJF, RR and priority based scheduling. Im supposed to read from a text file which looks something like this... except its a lot longers.. around 2100 processes.
Process Arrival Burst Priority
p1 ... | You'll probably need to implement each one of those scheduling algorithms and write some kind of simulator.
Instead of using arrays, as I always find it hard to remember what goes where, consider using a struct.
struct Process {
std::string name;
int arrival;
int burst;
int priority;
};
Then you can ch... |
5,468,194 | 5,468,209 | sort the 'std::vector' containing classes | Sort by using a binary predicate and std::sort
I need the sample for this...
| Here is another adaptation of the example that uses two different kinds of predicates. The predicate specified can be a function pointer or a functor which is a class that defines operator() so that the object when instantiated can be used just like a function would be. Notice that I had to add one more header inclusio... |
5,468,270 | 5,468,467 | SethreadAffinityMask() correct usage? | I have 1500 threads..I want them to run on 12 processors...
To do that I call
SetThreadAffinityMask(GetCurrentThread(),1<<(threadnum%numprocessors)); where numprocessors=12.
Is that correct usage of the mask?
It needs to be scalable, that is if i want it to run on just 11 processors, then
SetThreadAffinityMask(GetCurr... | Syntactically SetThreadAffinityMask(GetCurrentThread(),1<<(GetThreadId()%numprocessors)) it's correct but it's not a good idea to use affinity just because you have a lot of threads and processors. it can interfere with the scheduler and degrade performance. You can use this for some threads to minimize cache misses. ... |
5,468,346 | 5,468,388 | How to get the element in Vector using the specified position in c++? | How to get the element by providing position in vector template?
| You access std::vector elements just like a regular C array:
std::vector<int> myVector;
//(...)
int a = myVector[1];
|
5,468,850 | 5,469,027 | Find_if function in vector | Is this function sort the given vector array ?
Give your suggestions please
Regards,
vasantham
| Find_if is an function of an and returns an iterator to the first element in the range.
#include <list>
#include <algorithm>
#include <iostream>
bool greater10 ( int value )
{
if(value == 10)
{
return true;
}
return false;
}
int main( )
{
using namespace std;
list <int> ... |
5,468,889 | 5,468,924 | getting files off ftp connection | I have been given a project where i need to write a program which runs on a server. This program needs to open an ftp connection to another server and pick up a file and place it in a given folder.
I dont know where to start although i think i need some sort of socket prgramming... can anyone help me with where to sta... |
With Java, I would start from Apache Commons FTPClient.
With Python, I would start form ftplib.
With C++, you may find the answer here on SO.
|
5,469,030 | 5,469,561 | C++ - Play back a tone generated from a sinusoidal wave | Hey everyone, I'm currently trying to figure out how to play back a tone I have generated using a sinusoidal wave.
Here's my code:
#include <iostream>
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#include <Math.h>
using namespace std;
int main (int argc, char * const argv[]) {
int number = 0;
int i, size;... | I've written an example exactly for this. Runs fine with OpenAL under MacOSX and plays smooth sines. Take a look here:
http://ioctl.eu/blog/2011/03/16/openal-sine-synth/
Code is quite short, i guess i can add it here as well for sake of completeness:
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iostr... |
5,469,123 | 5,469,289 | What is the maximum size of an vector<>::maxsize()? | Please specify the range of vector list ....
I want to store million of records in vector<>.
I have to copy Millions of records from one vector<> to another vector<> and then sort the vector and apply my filter function(unique id) to retrieve the record.
is this possible in vector
Regards,
Karthik
|
What is the maximum size of an vector ....
I think you have answered your own question.
Theoretical limit for your system you can get with a function vector<T>::max_size(). For instance:
vector<int> vec;
std::cout<<vec.max_size()<<std::endl;//prints max size for vector<int> in your system!
So just run this and check... |
5,469,174 | 5,469,378 | How do I work with a C++ program containing non-Latin characters? | I have a C++ program that was written by a Russian-speaking developer and so it contains Cyrillic characters. When I open the sources they are displayed as garbage. How do I solve this in windows ?
| The actual problem is your IDE/editor doesn't display Cyrillic characters correctly. You solve this by changing the IDE/editor settings to use a font that contains Cyrillic characters - for example, Courier New if you're on Windows.
|
5,469,183 | 5,469,265 | WINAPI: how to get edit's text to a std::string? | I'm trying the following code:
int length = SendMessage(textBoxPathToSource, WM_GETTEXTLENGTH, 0, 0);
LPCWSTR lpstr;
SendMessage(textBoxPathToSource, WM_GETTEXT, length+1, LPARAM(LPCWSTR));
std::string s(lpstr);
But it doesn't work.
| You're using it absolutely incorrectly:
First, you are passing a type instead of a value here:
SendMessage(textBoxPathToSource, WM_GETTEXT, length+1, LPARAM(LPCWSTR));
Interfacing WinAPI functions who write to a string requires a buffer, since std::string's cannot be written to directly.
You need to define a space t... |
5,469,453 | 5,469,500 | A struct for putting in parameters passed around in a set of functions | I need the flexibility of being able to change parameters passed around to different functions, depending from where the call to the function happened, so I decided I'd put all my parameters in a struct, however most of these parameters are structs or classes themselves and I want to have the option of leaving them NUL... | To solve the problem of resource management, you should use boost::shared_ptr (or std::shared_ptr in C++0x).
struct A
{
boost::shared_ptr< otherB > b;
boost::shared_ptr< otherC > c;
};
void func(A& a)
{
a.b = boost::make_shared< otherB >();
}
A myA;
otherC somec;
myA.c = boost::shared_ptr< otherC >(&somec,... |
5,469,464 | 5,471,366 | How can I print values in C without specifying their types, like done with "cerr << (A) << endl" in C++? | In C++, having
#define DEBUG(A) cerr << (A) << endl;
I can send anything to it, and it can print it. However, in C, I must specify its type with %d, %c or %s etc. But I don't want to write its type all time, I want to use fprintf like cerr. How can I do that?
For example: in C
#define DEBUG(A) X // X is what I want to... | You can use GNU C Language Extensions :
#define DEBUG(x) \
({ \
if (__builtin_types_compatible_p (typeof (x), int)) \
fprintf(stderr,"%d\n",x); \
else if ... |
5,469,489 | 5,470,906 | Scaling Matrix and Translation Matrix related issue | Hi
I am setting a Unidirectional Scaling Matrix to an entity (say Entity 1) in 3D. Now, I have another entity (Entity 2 ) that follows this entity which is supposed to have uniform Scaling. The sequence of Matrix that I apply to both these entities is as follows ...
Translate entity1 from it's original world position ... | I will try to answer your last question first, hopefully it will make things clearer.
Whenever a graphic artist creates a building, a monster or a landscape, she will need to define a coordinate system. It consists in an origin (where is the 0,0) and some axises (where are the x and y directions?). The choice is comple... |
5,469,511 | 5,470,847 | What is multimap::emplace() and move()? | I was viewing the MSDN doc about multimap and find that it has a member function multimap::emplace(). Below is the example of that member function.
int main( ) {
using namespace std;
multimap<int, string> m1;
pair<int, string> is1(1, "a");
m1.emplace(move(is1));
}
It seems that emplace() and move() are C+... | Emplacing is easier to understand with vectors. my_vector.emplace_back(1, 2, 3) is basically an efficient shortcut for my_vector.push_back(some_type(1, 2, 3)). Instead of copy-constructing the object in-place, any constructor can now be used for in-place-construction, thus saving the creation, copy (or move) and destru... |
5,469,671 | 5,469,884 | Reading 6 bytes from filebuffer | Guys, i need to read 6 bytes from filebuffer and store them as unsigned number.
ifstream ifs("dummy.txt", ios::binary);
unsigned __int64 result = 0;
ifs.read((char*)&result, 6);
This is correct?
| First, the standard type of a 64 bit unsigned integer is either
'unsigned long long' or 'uint64_t'. And second, you have to know the
format of the data in the file you're reading. I've never seen a format
which uses six bytes, so it's difficult to guess, but supposing it's
binary, you should use either:
uint64_t read... |
5,469,692 | 5,474,099 | Why is my exception caught on some configurations and on others is not? | I have a program throwing an exception that is caught on some configurations (Suse Linux, g++ version 4.4.1) as expected but is obviously not caught on another, here: SunOS 5.10, g++ version 3.3.2. Following is the implementation of my exception class:
CException.hpp:
#ifndef _CEXCEPTION_HPP
#define _CEXCEPTION_HPP
#i... | I've found out that the problem is caused by the use of a Fortran95 compiler. It is used as a linker when building the program on a Sun machine, on other machines g++ is used. I have no idea what exactly the problem is but I think I'll just switch to g++ on the Sun machines as well.
|
5,469,775 | 5,469,816 | CRLF end of line and ostringstream | I am trying to use a ostringstream to build a string which uses the platform standard line endings (so for me it is CRLF since I am developing for Windows). I tried the following code:
std::ostringstream out;
out << "line1\nline2\n";
const char* result = out.str().c_str(); // In result end of lines are '\n' instead
... | Well, '\n' is the internal representation for end-of-line.
It is just when you write to an external file that it is converted (if needed!) to the external representation. On some systems the line ending is just one character, or even no character at all if stored with a hidden length value instead.
|
5,469,805 | 5,470,749 | How to enable a constructor with mpl techniques | I am little stuck with boost::enable_if and how to make a constructor switch with it.
The code is this:
struct NullType{};
struct TestType{};
struct NonNull{};
template<typename T, typename U = NullType>
struct TemplateStruct
{
TemplateStruct(int i, typename boost::enable_if<boost::is_same<U, NullType>, void* >::t... | This is one way to solve your problem as you want:
template<typename T, typename U = NullType>
struct TemplateStruct
{
TemplateStruct(int i)
{
boost::enable_if< boost::is_same<U,NullType>, void*>::type var = nullptr;
std::cout << "One Param == " << i << std::endl;
}
TemplateStruct(int i... |
5,469,918 | 5,469,984 | send/recv ethernet frame on windows using C++ | is there any windows library / kernel-mode driver (with usermode API) in C/C++ which I can use to send/recv ethernet frame without IP (only use mac address).
I heard about winpcap, is there any lighter library or wrapper to winpcap which has simple open(), close(), send(), recv() function?
| On unix there is hping http://www.hping.org/ and mausezahn http://www.perihel.at/sec/mz/ but I don't know if any of those compiles under windows. All applications/libraries I know are based on libpcap/winpcap.
|
5,470,331 | 5,470,350 | Traverse a List Using an Iterator? | I need sample for traversing a list using C++.
| The sample for your problem is as follows
#include <iostream>
#include <list>
using namespace std;
typedef list<int> IntegerList;
int main()
{
IntegerList intList;
for (int i = 1; i <= 10; ++i)
intList.push_back(i * 2);
for (IntegerList::const_iterator ci = intList.begin(... |
5,470,438 | 5,470,829 | Why are changes in source not always reflected in machine code after build while rebuild works? | Sometimes when I change code in my Qt project (Qt Creator 2.1.0 with mingw32), the changes don't get reflected in the produced machine code after building it. This happens mostly when I change things like default values in constructors or the order of parameters in methods/constructors. Usually, a full rebuild fixes t... | Usually, after a change in a header, all source files including that header should be rebuilt.
However, qmake is a bit peculiar in this regard, you need to set DEPENDPATH for include folders other than the current directory. E.g., if you have
INCLUDEPATH += somepath_in_my_project
also add
DEPENDPATH += some_path_in_my... |
5,470,811 | 5,475,155 | Write Base64 encoded text node with libxml2 | I have not found a proper tutorial on libxml2 yet and thus I'm struggling with some basic concepts, having "only" the API docs at hand, which are, IMHO, a little too brief in some points.
This is (C++) my attempt to write Base64 encoded data to a document (a text node as a child of the root element):
// create doc and ... | It appears that xmlTextWriterWriteBase64() needs the context of where to put the text. I was able to add the text to a new element via xmlTextWriterStartElement(), xmlTextWriterWriteBase64(), and xmlTextWriterEndElement(). You would think giving a node to xmlNewTextWriterTree() would set the context, but apparently i... |
5,470,863 | 5,471,113 | pre-calculating string length for va_list versions of _snprintf / _snwprintf | Is there a va_list style version of the following code to safely do a non-truncated sprintf:
// format a char buffer
int size = 1 + _snprintf(NULL, 0, "%d", 132);
std::vector<char> buffer (size);
sprintf_s(&buffer[0], buffer.size (), "%d", 132);
// format a wchar_t buffer
int wsize = 1 + _snwprintf(NULL, 0, L"%d", 132... | Visual Studio provides the _vscprintf function to check the amount of buffer needed to store the resulting string.
|
5,471,164 | 5,473,807 | Implementing Containers using Smart Pointers | Ok, so everyone knows that raw pointers should be avoided like the plague and to prefer smart pointers, but does this advice apply when implementing a container? This is what I am trying to accomplish:
template<typename T> class AVLTreeNode {
public:
T data;
unique_ptr<AVLTreeNode<T>> left, right;
int heig... | I do not usually use smart pointers when implementing containers as you show. Raw pointers (imho) are not to be avoided like the plague. Use a smart pointer when you want to enforce memory ownership. But typically in a container, the container owns the memory pointed to by the pointers making up the data structure.
... |
5,471,309 | 5,471,336 | Unresolved external symbol fail in VERY simple application | The simple code fails:
#include <Windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
MessageBox(NULL, L"Hello World!", L"Just another Hello World program!", MB_ICONEXCLAMATION | MB_OK);
return 0;
}
Errors:
Error 1 error LNK2019: unresolved external... | The program's entry point is where execution starts at. For a console application, this defaults to main. For a Windows application with no console, this defaults to WinMain.
The linker is searching for main, most likely because you created a console application. Go into your project settings and change the subsystem t... |
5,471,317 | 5,471,341 | Why char *x not char x? | I've a code
#include <iostream>
using namespace std;
void foo(char *name){ // ???
cout << "String: " << name << endl;
}
int main(){
foo("Hello");
return 0;
}
I don't know why I use "char name" won't work. Please help.
Cheers,
| A string can be represented as an array of char(s). You can use the char * pointer to refer to that string.
You could use char name with foo('c'), because that's a char.
|
5,471,476 | 5,471,505 | Smart-pointer template operator overload failing due to error C2244: "unable to match function definition to an existing declaration" | I have looked for dupes of this but forgive me if I missed a solution.
I have a smart pointer that has 2 comparison overloads, "==" and "<". Both of these operate on the underlying pointer only (inherited code before I am chastised). However on compilation I am getting a C2244 error for both. I will present the case f... | You're lacking a const in the definition.
template <class TypeRefObj>
inline int SmartRef< TypeRefObj >::operator==
( const SmartRef< TypeRefObj > & roTheValue ) const
Also, you should define the member functions in the header - #include of a .cpp like you do doesn't do much for readability.
|
5,471,518 | 5,471,969 | advice on an oo planing | I am trying to develop an object oriented representation of a finite element model. The finite element model consists of some output files(outputs of a commercial Finite element program) in binary format which keep certain data related to the finite element model (for people who are not in the field, these data corresp... | My that's a bit of a wall of text. It could use a bit of filtering/rewriting.
As I understand it you have several files representing your 3D elements etc.
I nice OO way of doing it (at least in my mind) would be to have a separate class for each type of file you want to load, pass the filename in the constructor and lo... |
5,471,807 | 5,471,833 | vector::clear :Memory Issue | Vector::Clear() will erase the elements in the vector array.
The issue is that if we pass objects in vector list then Clear() will delete the memory of objects or not.
I post my sample:
CData *m_data = new CData();
vector<CData*> m_logdata;
m_logdata.push_back(m_data);
m_logdata.clear();
will this ... | There's no Vector, there is a vector though.
vector.clear() will destruct the objects in the vector. If these objects are pointers, it will not delete the pointed to objects.
struct Foo {
};
vector<Foo> vec1;
vector<Foo *> vec2;
vec1.push_back(Foo());
vec2.push_back(new Foo());
vec1.clear(); // Will destruct the Foo... |
5,471,838 | 5,471,930 | Compile ImageMagick in a single DLL | My application is built with C++/MFC and links dynamically with ImageMagick. I have to deploy 130 (!) ImageMagick DLLs alongside my files when installing the app!
I would like to have a single DLL for the entire ImageMagick library instead of 130. Any ideas for how to do that?
| The DLL uses the serach path. Place the ImageMagick.DLL in one directory that is included in the PATH.
If that's not possible, you can change the PATH variable. Add a path to the directory where one instance of the DLL resides.
|
5,471,874 | 5,471,985 | Contiguous memory guarantees with C++ function parameters | Appel [App02] very briefly mentions that C (and presumably C++) provide guarantees regarding the locations of actual parameters in contiguous memory as opposed to registers when the address-of operator is applied to one of formal parameters within the function block.
e.g.
void foo(int a, int b, int c, int d)
{
int... | First of all your code doesn't always produce 1, 2, 3, 4. Just check this one: http://ideone.com/ohtt0
Correct code is at least like this:
void foo(int a, int b, int c, int d)
{
int* p = &a;
for (int i = 0; i < 4; i++)
{
std::cout << *p;
p++;
}
}
So now let's try with fastcall, here:
vo... |
5,472,005 | 5,472,276 | Deploy QT apps in Mac OS X | I have created an app in QT & I am able to deploy it in Windows.
But in Mac I am facing problems.
Can any one help me how to do this?
I am using the commands as said in help files & when I type qmake -config release i get ::::"Failure to open file: /Developer/Examples/Qt/mainwindows/application///application.xcodepro... | With the lack of information regarding the problem that you are facing I can only recomend you to read the info provided in the Qt Reference Documentation.
http://doc.trolltech.com/4.7/deployment-mac.html
|
5,472,102 | 5,473,653 | get subclass type through the base class pointer | Given the class layout (Base->Derived; Base->Derived2), and the fact that I hold the instance to the derived classes as base class pointer (Base* baseder2 = new Derived2), I'd like to be able to instantiate the TemplClass instance with the derived type (something like sh = new TemplClass<Derived2>(baseder2)). The code ... | Is template class really needed in your situation? In the given example you may add method "function" to the base class, and make it virtual.
But if you still need template classes, following is possible:
class Base
{
public:
virtual ~Base(){}
virtual BaseTemplClass* createTemplClass() = 0;
};
class Derived : publ... |
5,472,115 | 5,472,408 | Is this code behavior defined? | What does the following code print to the console?
map<int,int> m;
m[0] = m.size();
printf("%d", m[0]);
Possible answers:
The behavior of the code is not defined since it is not defined which statement m[0] or m.size() is being executed first by the compiler. So it could print 1 as well as 0.
It prints 0 because the ... | I believe it's unspecified whether 0 or 1 is stored in m[0], but it's not undefined behavior.
The LHS and the RHS can occur in either order, but they're both function calls, so they both have a sequence point at the start and end. There's no danger of the two of them, collectively, accessing the same object without an ... |
5,472,332 | 5,472,713 | How to convert a C++ structure into a database | I have a software which use differents structures for its configuration. Each time i save the configuration the structures are dump into a binary file and each time i load the config the files are read and structures are populated with the data.
For some reason i would like to change this and use a database for storing... | There are quite some things you need to take into account.
First of all, do you want your database to have a readable structure or not? Or can you live with quite unreadable data in the database, but better suited for mapping to your structure?
If you want a readable database structure (preferably in a 3th or 4th nor... |
5,472,368 | 5,472,403 | How to define member function coming from non-template base class | I have a non-templated abstract base class. How do I define the pure virtual function outside derived class?
#include <iostream>
class base {
public:
virtual void func() = 0;
};
template<typename T>
class der : public base{
};
template<typename T>
void der<T>::func()... | Declare the member function.
template<typename T>
class der : public base{
public:
void func();
};
There's no automatic declaration of member functions that you may or may not wish to override in a derived class - you have to explicitly declare and define these. Whether the derived class is impleme... |
5,472,411 | 5,472,692 | How does initialization of two-dimensional arrays work? | came across the code shown below in a small C++ example:
int (*arr1)[ARRAY_SIZE];
int (*arr2)[ARRAY_SIZE];
int (*arr3)[ARRAY_SIZE];
then in the constructor of the class:
ParallelMultiply::ParallelMultiply(int mat1[ARRAY_SIZE][ARRAY_SIZE],
int mat2[ARRAY_SIZE][ARRAY_SIZE],
int ... | You may be familiar with the way an array can decay to a pointer and then that pointer can be used like an array (as long as its actual extent is known).
When this sort of thing is done to a multidimensional array, you get a pointer to array with one less array bound. Then that pointer can be used like the multidimens... |
5,472,684 | 5,472,700 | C++ do stack memory allocation/deallocation defragement memory | C++ do stack memory allocation/deallocation defragement memory.
when i declare local memory variables, they are allocated and deallocated, does it makes memory fragemented?
this can be very important from memory point of view
how much memory is availabe for stack?
can I allocate
char sam[999999999999999];
| No, memory is not fragmented. How much memory you can allocate on stack is implementation-defined, usually something around 1 megabyte.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.