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 |
|---|---|---|---|---|
1,546,494 | 1,546,538 | Google Earth and Windows application | I have a C++ Windows application continually updating lat, long and altitude.
I would like my application to incorporate Google Earth to visually "track it".
Any advice or pointing in the right direction would be appreciated.
Thanks.
| You can embed the Google Earth plugin into your application as an ActiveX control. The API for the control can be found here. You need to instantiate your GEPlugin control and from here you can retrieve all the other COM objects. There is no need to register with Google for the development key. This is not supported by... |
1,546,789 | 1,669,254 | Clean code to printf size_t in C++ (or: Nearest equivalent of C99's %z in C++) | I have some C++ code that prints a size_t:
size_t a;
printf("%lu", a);
I'd like this to compile without warnings on both 32- and 64-bit architectures.
If this were C99, I could use printf("%z", a);. But AFAICT %z doesn't exist in any standard C++ dialect. So instead, I have to do
printf("%lu", (unsigned long) a);
w... | Most compilers have their own specifier for size_t and ptrdiff_t arguments, Visual C++ for instance use %Iu and %Id respectively, I think that gcc will allow you to use %zu and %zd.
You could create a macro:
#if defined(_MSC_VER) || defined(__MINGW32__) //__MINGW32__ should goes before __GNUC__
#define JL_SIZE_T_SPEC... |
1,546,997 | 1,547,287 | Will accessing a class object through a pointer to its derived class break strict aliasing rules? | void foobar(Base* base)
{
Derived* derived = dynamic_cast<Derived*>(base); // or static_cast
derived->blabla = 0xC0FFEE;
if (base->blabla == 0xC0FFEE)
...
}
On compilers with strict aliasing, is "derived" an alias for "base"?
| Two pointers are aliased whenever it is possible to access the same object through them. Paragraph 3.10/15 of the standard specifies when an access to an object is valid.
If a program attempts to access the stored value of an object through an lvalue of other than one of the following types the behavior is undefined:
... |
1,547,010 | 1,547,243 | When to use OOP instead of Arrays | When should I use OOP instead of an array? Does the size of my project matter?
To provide a little background: I'm making a small program for my friend. Basically, he wants to add different scores to each other to be able to see his grade. (Yes, I know there's commercial software, but this is also a fun exercise.) Anyw... | Agreed with others, arrays and OOP are two different and overlapping concepts. It's like saying, "How should I get to work today? On time, or in a car?" You can do both/either/neither, they are two different things.
Assuming you have one person (your friend) in the program with a set of scores, and you add all the s... |
1,547,066 | 1,547,080 | How do we iterate through all elements of a set while inserting new elements to it? | consider this:
// set_iterator.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <set>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
set<int> a1;
set<int> a2;
a1.insert(3);
a1.insert(4);
a1.insert(5);
a2.insert(1);
a... | Actually, the iterator is still valid. A set is a node-based container.
The problem is that in a set the elements are always sorted. Before insertion, your set looks like this:
3 4 5
^
iter
After insertion, your set looks like this:
1 2 3 4 5 6
^
iter
You'll have to use a different container if you want to be... |
1,547,092 | 1,547,098 | Stream Insertion Overloading C++ | Im trying to call the function:
friend ostream& operator<<(ostream& out, stack::myItem& theItem);
that is public to my stack object:
class stack
{
public:
stack(int capacity);
~stack(void);
void method1();
...
private:
struct myItem
{
int item;
};
...
publi... | If you are looking to call it on the myItem struct, then:
for ( int i = 0; i < s.count; i++ )
{
if ( i < s.count-1 )
out << s.myItem[i] << ", ";
else out << s.myItem[i];
}
would call it on each struct in the stack.
In the endlessly recursive one, you are just calling it again on the stack, and in the f... |
1,547,211 | 1,547,251 | How to create minidump for my process when it crashes? | I am not able to create minidump form my process by changing system setting. So my Question is
:
Will the system create a minidump for a user process when it crashes
If yes, which setting do I need to configure
Or do I have to create minidump programmatically.
How effective are minidumps while investigating a crash
... | You need to programatically create a minidump (with one exception, see next link). CodeProject has a nice article on MiniDumps. Basically, you want to use dbghelp.dll, and use the function MiniDumpWriteDump() (see MSDN on MiniDumpWriteDump).
How effective such dumps are depends very much on the application. Sometime... |
1,547,342 | 1,557,354 | C++ run time error with protected members | I am trying to do a homework assignment where we insert a string into a string at a specified point using a linked stack, hence the struct and typedef. Anyway, when I try to access stringLength in the StringModifier class inside the InsertAfter method, I get a run time error and I cannot figure out what the problem is.... | Thanks for everyone's help. It turns out I was adding things to the list wrong to begin with. Instead of making it a stack I made it a Queue and all is working great! I took advice you guys gave and looked elsewhere for the problem. Thank You!
void String::SetString()
{
StringPointer p, last;
char tempCh;
l... |
1,547,621 | 1,547,656 | General printing raster and/or vector images | I'm looking for some API for printing.
Basically what I want to achieve is to print set of pixels(monochromatic bitmap which I store in memory) onto the generic paper format (A4,A5..etc.).
What I think that would be minimum API is:
printer devices list
printer buffer where I could send my in-memory pixmap (ex. like wi... | Well you got close, look at Printing in Qt. There is the QPrinter class that implements some of what you are looking for. It is implmenetent as a QPaintDevice. This means that any widget that can render itself on the screen can be printed. This also mean you don't need to render to a bitmap to print, you can use Qt wid... |
1,547,632 | 1,548,638 | Programming in gamedev (performance related) | I am just wondering how some things work in gamedev:
I know, that the performance is actually crucial so there is still (and I think never will be) no place to use managed languages/platforms as Java/.NET just because of their performance. But... recently I have read somewhere here on SO, that even though people creat... | It is true that in game development, STL is not used. In spite of what certain people always rush to claim, they also never use Java or C# or other managed languages.
I'm not talking about small X-Box Live Arcade downloadable games or web browser games, or such things. I'm talking about high-end development in AAA ga... |
1,547,746 | 1,548,429 | C++ Passing two dimensional arrays as parameters to classes | I've got a Car class and a Track class. The Car class constructor takes a road parameter which is supposed to be a 32x32 boolean array. Then I've got a Track class which creates a Car class and is supposed to pass the 32x32 array to it's constructor.
Note that I've simplified the code somewhat by removing irrelevant ... | You can't copy arrays like that. Others have already discussed this in more detail, including alternative for-loop individual assignment and memcpy solutions.
Another solution is to wrap your array inside a struct. Struct's can be copied like that.
E.g.:
struct RoadStruct
{
bool road[32][32];
};
class Car : public... |
1,547,790 | 1,547,807 | How to assign a value to a TCHAR array | I have a TCHAR array in my C++ code which I want to assign static strings to it.
I set an initial string to it via
TCHAR myVariable[260] = TEXT("initial value");
Everything works fine on this. However, when I split it in two lines as in
TCHAR myVariable[260];
myVariable = TEXT("initial value");
it bugs and gives a co... | The reason the assignment doesn't work has very little to do with TCHARs and _T. The following won't work either.
char var[260];
var = "str"; // fails
The reason is that in C and C++ you can't assign arrays directly. Instead, you have to copy the elements one by one (using, for example, strcpy, or in your case _tcsc... |
1,547,864 | 1,547,876 | Pointer to class method | I'm trying to have pointer to class methods, so I have something like:
class foo {
public:
static void bar() {
}
};
void (foo::*bar)() = &foo::bar;
That doesn't compile :( I get:
> error: cannot convert ‘void (*)()’ to
> ‘void (foo::*)()’ in
> initialization
| A static method, when used by name rather than called, is a pointer.
void (*bar)() = foo::bar; // used as a name, it's a function pointer
...
bar(); // calls it
|
1,547,870 | 1,547,892 | Why is my nest class being seen as abstract? | I have an abstract base class which contains a private nested implementation. visual c++ is giving me the following error when I try to instantiate the non-abstract nested implementation:
error C2259: 'node::empty_node' : cannot instantiate abstract class (line 32)
as far as I can tell, I've overridden all the abstrac... | The function signatures don't match. The pure virtual member functions in the base class 'node' are not const; the functions in the derived class 'empty_node' are const.
You either need to make the base class virtual functions const or remove the const qualifier from the member functions in the derived class.
|
1,547,958 | 1,547,968 | Why am I getting unresolved externals? | I am writing an immutable binary search tree in c++. My terminating nodes are represented by a singleton empty node. My compiler (visual c++) seems to be having trouble resolving the protected static member that holds my singleton. I get the following error:
error LNK2001: unresolved external symbol "protected: stat... | m_empty is static and so you'll need to have a source (.cpp) file with something like the following:
template <typename K, typename V> shared_ptr<node<K,V> > node<K,V>::m_empty;
Note: My original answer was incorrect and did not take into account that this was a template. This is the answer that AndreyT gave in his ... |
1,547,991 | 6,095,469 | Invalid Class String Error when creating C++ Project in Visual Studio 2008 with Vista x64 | After going through this Problem (connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=329986) that was related with registry permissions, now again, Visual Studio comes with another error.
I have the same error as this guy, I have searched all the internet and it seems nobody has resolved it yet.
W... | Well this hapend to me after i renamed feacp.dll in order to disable intellisense.
However, after re-enabling intellisense, all worked ok.
|
1,548,017 | 1,553,978 | How to include a newline in a C++ macro or how to use C++ templates to do the same? | I saw the following question:
How to generate a newline in a cpp macro?
Let me give a brief requirement of a need in newline in a C++ preprocessor. Am working on ARM Realview compiler 3.1 on a code which uses embedded assembly code with C++ code.
#define DEFINE_FUNCTION(rtype, op, val) \
__asm rtype nt_##op(void*) ... | I solved the above problem using GNU m4 preprocessor successfully.
m4_define('DEFINE_FUNCTION','
__asm rtype nt_$2(void*) {
str lr, [sp, $3];
bl vThunk_$1;
ldr lr, [sp,$3];
bx lr;
}
void vThunk_$2(void*)')
DEFINE_FUNCTION(void*, mov_lt, 0x04)
{
}
Preprocessing the above code us... |
1,548,075 | 1,548,867 | Signing data in C++ compatible with PHP's openssl library | I'm looking for a way to sign some data in C++ code which will then be sent to a PHP script for verification and processing. I want to use the OpenSSL module there, namely the openssl_verify function so I need something compatible with that.
The application will be only for Windows so CryptoAPI might be fine but lookin... | As for the Cripto API this example might help you to import a custom private key.
Alternatively, you can look at Crypto++.
|
1,548,495 | 1,548,795 | Can a program figure out its Oracle resource usage? | My boss would like to find a way for a running executable to ask Oracle, the size of the resources that the program is used. The purpose behind this is so that we can add to the
user documentation/capacity planning documentation information on the size of the resources needed for each program.
My Google-Fu is weak t... | This query will show you session statistics by their description.
select v$statname.name, v$mystat.value
from
v$mystat,
v$statname
where
v$mystat.statistic# = v$statname.statistic#
Descriptions of the various statistics (for 10g) are here:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/stat... |
1,548,658 | 1,548,666 | C++ Error: No Match for Call | I'm trying to compile the following code in C++
string initialDecision ()
{
char decisionReviewUpdate;
cout << "Welcome. Type R to review, then press enter." << endl;
cin >> decisionReviewUpdate;
// Processing code
}
int main()
{
string initialDecision;
initialDecision=initialDecision();
//ERROR OC... | Don't give your string and your function the same name, and the error will go away.
The compiler has "forgotten" that there is a function with that name, when you declare a local variable with the same name.
|
1,548,686 | 1,548,995 | functor generation from member function pointer type | I am trying to simplify (via make_fn()) the generation of functors that preprocess parameters (via wrap()) for member functions of arity n.
Generating the functors is basically working, but until now only by explicitly specifying the parameter types for the member function.
Now i'd like to generate the correct functor ... | It appears to me that you are attempting to turn a pointer passed to a function into a non-type template argument, which I'm afraid is not going to work (see comments to your question).
What you could do, is to store the function pointer in a function object. The following appears to compile:
#include <boost/bind.hpp>
... |
1,548,741 | 1,548,789 | Check if mouse is over a rotated sprite? C++ | I'm making a game in c++. It is a card game. I have made 13 cards that rotate about a point to arc out to make your hand. I need a way to figure out which card the user clicks on. My cards are basically rectangles rotated about a point that is in the center of the cards. I was thinking of maybe getting the mouse point ... | Rotating a around p
The trick is to reduce rotating around a point to rotating around the origin by doing translations.
Subtract p from a (move to the origin)
Rotate by angle
Add p to resulting point (move again)
Formula for rotating (x, y) aroung the origin:
|
1,548,947 | 1,548,967 | Passing one va_list as a parameter to another | I'm creating an application using the fastcgi library, and their method of printing is a little verbose. I'm trying to wrap their fprintf function in my own method:
I would like to turn
FCGX_FPrintF(out, char* fmt, ...);
into
write(char* strFormat, ...);
I've found the magic of va_list but can't find an easy way to... | You would have to find the analogue of vfprintf() in the Fast CGI library. It is at least moderately plausible that there is one; the easy way to implement FCGX_FPrintF() is:
void FCGX_FPrintF(FILE *out, char *fmt, ...)
{
va_list args;
va_start(args, fmt);
FCGX_VFPrintF(out, fmt, args);
va_end(args);
}... |
1,548,986 | 1,549,007 | Array Manipulation in C++ | Help me understand this piece of code -
After the first iteration the value of PlcCode becomes A1*. How come? Shouldn't it be A*?
Code = "A1";
char Wild = '*';
TDataString PlcCode(Code);
for (int i = (Code.Len() - 1); i >= 0; i--)
{
PlcCode[i] = Wild;
}
| Another possibility
TDataString is storing non-null terminated data, and has a templated operator= accepting byte arrays.
This way, you could think of the code as
TDataString Code(3);
Code[0] = 'A';
Code[1] = '1';
Code[2] = '\0';
char Wild = '*';
TDataString PlcCode(Code);
for (int i = 2; i >... |
1,549,093 | 1,549,141 | LNK2019 && LNK1120 errors when splitting my code in multiple files | My code is stored in a main.cpp file which contains the void main() function, and a class MyClass which I now want to split to another file. IDE is Microsoft Visual Studio 2008 Professional.
myclass.h
#include <tchar.h>
class MyClass {
public:
static bool MyFunction (TCHAR* someStringArgument);
};
myclass.cpp
#inc... | You declared two classes here. One of them is in myclass.h and the other is in myclass.cpp. Try the following instead:
myclass.h
#ifndef myclass_h_included
#define myclass_h_included
#include <tchar.h>
class MyClass {
private:
static bool someProperty;
static void doSomeOneTimeCode ();
public:
static boo... |
1,549,129 | 1,671,618 | Debugging image rendering in Visual C++, any helpful add-ins? | I often write code that renders images by writing pixels directly into buffers and I often find it hard to get a good overview of what's really going on. The Memory window in Visual Studio's debugger is somewhat a help, but I'd really love to see the images graphically.
So my question is, does anyone know of a debuggin... | Such a thing exists:
A utility for simple printf-style debugging of images in Win32 C/C++ applications.
http://billbaxter.com/projects/imdebug/
My coworker raves about it.
--chris
|
1,549,130 | 1,549,138 | Accessing a member/method of a virtual derived class | The example here doesn't make sense, but this is basically how I wrote my program in Python, and I'm now rewriting it in C++. I'm still trying to grasp multiple inheritance in C++, and what I need to do here is access A::a_print from main through the instance of C. Below you'll see what I'm talking about. Is this possi... | Make either B or C inherit from A using "public virtual" instead of just "virtual". Otherwise it's assumed to be privately inherited and your main() won't see A's methods.
|
1,549,176 | 1,549,190 | C++ - Using std::count() with abstract data types? | My code is using std::count() on a list of an abstract data type that i have defined. (Sommet or Edge in english). But it doesn't work, although i've overloaded the < and == operators like this :
bool operator< (const Sommet &left, const Sommet &right)
{
if(left.m_id_sommet < right.m_id_sommet)
return true;
re... | It looks like you are passing in an iterator as the last parameter to std::count whereas you need to pass in a value (by const reference).
Post edit: it looks like I was correct, you are passing iter which is an iterator. You need to dereference it first. Try passing *iter instead.
|
1,549,184 | 1,549,199 | Something like print END << END; in C++? | Is there anyway to do something like PHP's
print << END
yadayadayada
END;
in C++? (multi-line, unescaped, easy-to-cut-and-paste stream insertion)
| This answer is now out of date for modern C++ - see sbi's answer for the modern way.
This is the best you can do:
std::cout <<
"This is a\n"
"multiline\n"
"string.\n";
Not as convenient as a proper heredoc, but not terrible.
|
1,549,447 | 1,549,460 | Why is MSVC throwing a tantrum compiling a macro while G++ is all about zen? | Under MSVC 9.0, this fails. Under g++ this compiles. If we take out the macro then the non-macro version 76-79 compiles. Any ideas?
03: #include <iostream>
04: #include <sstream>
67: #define MAKESTRING(msg, v) \
68: do { \
69: std::ostringstream s; \
70: s << msg; \
71: v = s.str(); \... | I would make sure that you don't have any trailing whitespace after the backslashes that you use to separate the lines of your macro. Since the compiler is reporting line numbers that are within your macro definition, it means the preprocessor hasn't quite done what you expect.
Also try running this with the MSVC /E co... |
1,549,634 | 1,550,136 | Qt: QImage always saves transparent color as black | How do I save a file with transparency to a JPEG file without Qt making the transparent color black?
I know JPEG doesn't support alpha, and the black is probably just a default "0" value for alpha, but black is a horrible default color.
It seems like this should be a simple operation, but all of the mask and alpha func... | I'd try something like this (i.e., load the image, create another image of the same size, paint the background, paint the image):
QImage image1("someFile.png");
QImage image2(image1.size());
image2.fill(QColor(Qt::white).rgb());
QPainter painter(&image2);
painter.drawImage(0, 0, image1);
image2.save("somefile.jpg", "J... |
1,549,843 | 1,549,902 | c/c++ XML library question | I know that a lot of c/c++ XML library questions have been asked already (I tried to read through all of them before getting to this).
Here are the things I'm going to need in my own project:
Excellent performance
SAX2
Validation
Open source
Cross platform
I was going to use Xerces-C, but I see that a simple SAX2 set... | Having spent a goodly amount of time on this same problem, it was my conclusion that libxml2 is the best option available under your guidelines. The C interface is not too difficult to use and it's very fast.
There are some other good options for commercial libraries, but most of the other comparable open-source option... |
1,549,869 | 1,549,876 | What does const mean following a function/method signature? | According to MSDN: "When following a member function's parameter list, the const keyword specifies that the function does not modify the object for which it is invoked."
Could someone clarify this a bit? Does it mean that the function cannot modify any of the object's members?
bool AnalogClockPlugin::isInitialized() c... | It means that the method do not modify member variables (except for the members declared as mutable), so it can be called on constant instances of the class.
class A
{
public:
int foo() { return 42; }
int bar() const { return 42; }
};
void test(const A& a)
{
// Will fail
a.foo();
// Will work
... |
1,549,930 | 1,549,937 | C++ equivalent of Java's toString? | I'd like to control what is written to a stream, i.e. cout, for an object of a custom class. Is that possible in C++? In Java you could override the toString() method for similar purpose.
| In C++ you can overload operator<< for ostream and your custom class:
class A {
public:
int i;
};
std::ostream& operator<<(std::ostream &strm, const A &a) {
return strm << "A(" << a.i << ")";
}
This way you can output instances of your class on streams:
A x = ...;
std::cout << x << std::endl;
In case your operat... |
1,549,941 | 1,549,960 | Perfect square and perfect cube | Is there any predefined function in c++ to check whether the number is square of any number and same for the cube..
| No, but it's easy to write one:
bool is_perfect_square(int n) {
if (n < 0)
return false;
int root(round(sqrt(n)));
return n == root * root;
}
bool is_perfect_cube(int n) {
int root(round(cbrt(n)));
return n == root * root * root;
}
|
1,549,949 | 1,549,962 | Segmentation fault only when I redirect stdout to /dev/null? | I've got a C++ unit test that produces useful output to stderr, and mostly noise (unless I'm debugging) to stdout, so I'd like to redirect the stdout to /dev/null.
Curiously enough, doing this seems to cause a segmentation fault.
Is there any reason why code might seg fault with "> /dev/null" and run fine otherwise?
Th... | There is no 'normal' reason for I/O to stdout to trigger a core dump when standard output is redirected to /dev/null.
You most probably have a stray pointer or a buffer overflow that triggers the core dump when sent to /dev/null and not when sent to standard output - but it will be hard to spot the problem without the ... |
1,549,990 | 1,550,034 | in which area is c++ mostly used? | I've been asked many times by my juniors about the areas in which C++ is widely used. I usually answer Operating Systems. Are there any other areas where its extensively used?
| A quite large and probably quite definitive list of software written in C++ can be found at Bjarne Stroustrup's homepage.
|
1,550,070 | 1,550,085 | changing part of a file in C++ | Consider i have a file, 'emp.txt' whose content is,
EmpNo. Name Phone No. Salary
1 ABC 123 321
2 CBA 456 543
Now i want to change the phone no. 1st Employee alone. When i tried using ios:ate, all the contents of the file got deleted and the new phone no. got inserted. How can... | If you open a file for just output, the library usually truncates the existing file. To change the existing contents of a file, the easiest way is to open it in 'read/write' mode so that you can seek to the correct position and partially overwrite its contents.
Try something like:
std::fstream filestream( "emp.txt", st... |
1,550,091 | 1,550,106 | How to compare two pointers to object by their most derived type? | I have a following class hierarchy:
class Base{
....
virtual bool equal(Base *);
}
class Derived1: public Base{
....
virtual bool equal(Base *);
}
class Derived2: public Derived1{
}
class Derived3: public Derived1{
}
class Derived4: public Base{
}
How I should write Base::equal(Base *) function such that compares Der... | I think you can use typeid operator here. You can do something like:
typeid(*pointerBase) == typeid(*this);
But why do you want to do something like this? It looks very suspicious, I suggest to take a relook at the design.
|
1,550,292 | 1,550,300 | C++: Element types in a tuple | std::pair has the nested typedefs first_type and second_type which give the type of the first and second element respectively.
But is there any way to statically determine the type of the Nth element in a boost::tuple (or std::tuple in C++0x)? I know I could create my own template with N as a parameter, and use it to ... | http://www.boost.org/doc/libs/1_40_0/libs/tuple/doc/tuple_advanced_interface.html
In C++0x it will work similarly. But I think it has been renamed to tuple_element<I,T>::type
|
1,550,315 | 1,550,357 | How to catch exception from CloseHandle() | As of the MSDN spec, CloseHandle throws an Exception if an invalid handle is passed to it when it runs under a debugger.
Since I want to have clean code, I've inserted some code to catch it. However, it doesn't work, the exception gets uncaught.
#include <windows.h>
#include <tchar.h>
#include <exception>
/* omitted co... | You have two options:
Option 1:
Use SEH, you need to write something like this:
__try
{
// closeHandle
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
// print
}
Option 2:
Use the compiler switch /EHa, which will instruct the compiler to emmit code which will allow you to handle SEH exception via C++ style exception hand... |
1,550,329 | 1,550,334 | How can I indent cout output? | I'm trying to print binary tree
void print_tree(Node * root,int level )
{
if (root!=NULL)
{
cout<< root->value << endl;
}
//...
}
How can I indent output in order to indent each value with level '-' chars.
| You can construct a string to contain a number of repitions of a character:
std::cout << std::string(level, '-') << root->value << std::endl;
|
1,550,354 | 1,550,405 | Visual C++ studio, recompiling only the modified files | I have two dll files made by around 1500 cpp files. When I need to edit one, I usually then recompile all the 1500 files from the start. But I heard there is a way to make Visual Studio recompile the modifies only, taking a lot less time... How do I do this?
| VS is actually pretty good in doing the dependency checks so that only necessary stuff is re-compiled. I can see a couple of (more or less likely) reasons for what you're seeing:
You modify a header and that's been included everywhere.
You're hitting "rebuild" instead of "build".
You have included a cpp file.
Some... |
1,550,370 | 1,550,459 | C++: Polymorphic class template | Consider a class Calendar that stores a bunch of Date objects.
The calendar is designed to hold a collection of any type of objects that inherit from Date. I thought the best way to do it is to have a class template such as
template<typename D> class Calendar{
...
}
But it struck me that D can now in fact be any ... |
I know how to do this is Java, but I'm still unfamiliar with the C++ syntax. The problem is very much similar to how some collections can only take a template variables that implement Comparable. The header would then look something like
public class Calendar<D extends Date>{
...
}
True, it is the same problem,... |
1,550,561 | 1,550,570 | Prepending a string to another string | Currently, I have this code to prepend a "tag" to an exception message which gives me a very light version of a stack trace:
try {
doSomething();
} catch (std::exception& e) {
int size = 8 + _tcslen(e.what());
TCHAR* error = new TCHAR[size];
_sntprintf(error, size, TEXT("myTag: %s"), e.what());
std:... | what about something like this:
throw std::exception(std::string("myTag: ").append(e.what()).c_str());
Added a call to c_str() and tested it in Visual Studio and it works (side note: this doesn't compile in gcc, there's only a default constructor in the implementation).
|
1,550,648 | 1,550,675 | template which enforces interface | Is it possible to create a template accepting types which implement certain interface?
For example, I want to say to template user: you can store anything in my container as long as it implements Init() and Destroy() methods.
Thanks
| A limited subset of the (intended, but unfortunately cut) C++0x functionality of concepts is provided by the Boost Concept Check library. You can harness it by creating a concept check class for your required interface.
|
1,550,686 | 1,550,696 | Are c styled strings safe? | In c/c++ some people use c-styled strings like:
char *str = "This is a c-styled string";
My question is is this safe? The way I see it is they created a char pointer that points to the first letter of a const array of chars, but can't some other thing eg another variable overwrite a portion of the char array in the me... | These days string constants are placed in read-only sections of your binary. If you attempt to write to an address in a read-only section the CPU's memory management unit will cause a fault and your application will get an access violation or segmentation fault or some other operating system dependent behavior.
Also, ... |
1,550,721 | 1,551,253 | python struct.pack equivalent in c++ | I want a fixed length string from a number just like struct.pack present in python but in c++. I thought of itoa (i,buffer,2) but problem can be that its length will depend on platform. Is there any way to make it independent of platform ?
| If you're looking for a complete solution similar to Python's struct package, you might check out Google's Protocol Buffers Library. Using that will take care of a lot of issues (e.g. endian-ness, language-portability, cross-version compatibility) for you.
|
1,550,770 | 1,550,786 | How to check for division by 7 for big number in C++? | I have to check, if given number is divisible by 7, which is usualy done just by doing something like n % 7 == 0, but the problem is, that given number can have up to 100000000, which doesn't fit even in long long.
Another constrain is, that I have only few kilobytes of memory available, so I can't use an array.
I'm ex... | Think about how you do division on paper. You look at the first digit or two, and write down the nearest multiple of seven, carry down the remainder, and so on. You can do that on any abritrary length number because you don't have to load the whole number into memory.
|
1,550,844 | 1,550,863 | How to use string indexes in c++ arrays (like php)? | How can I use a string index in a c++ array (like in php)?
| You could use std::map to get an associative container in which you can lookup values by a string index. A map like std::map<std::string, int> would associate integer values with std::string lookup keys.
|
1,550,904 | 1,553,597 | Stuck building a game engine | I'm trying to build a (simple) game engine using c++, SDL and OpenGL but I can't seem to figure out the next step. This is what I have so far...
An engine object which controls the main game loop
A scene renderer which will render the scene
A stack of game states that can be pushed and popped
Each state has a collectio... | A 'queueTriangle' call sounds to me to be very inefficient. Modern engines often work with many thousands of triangles at a time so you'd normally hardly ever be working with anything on the level of a single triangle. And if you were changing textures a lot to accomplish this ordering then that is even worse.
I'd reco... |
1,550,910 | 1,550,926 | C++ and Java performance | this question is just speculative.
I have the following implementation in C++:
using namespace std;
void testvector(int x)
{
vector<string> v;
char aux[20];
int a = x * 2000;
int z = a + 2000;
string s("X-");
for (int i = a; i < z; i++)
{
sprintf(aux, "%d", i);
v.push_back(s + aux);
}
}
int ma... | You have to be careful with performance tests because it's very easy to deceive yourself or not compare like with like.
However, I've seen similar results comparing C# with C++, and there are a number of well-known blog posts about the astonishment of native coders when confronted with this kind of evidence. Basically ... |
1,550,997 | 1,551,248 | CreateProcessWithLoginW - Redirecting STDOUT | What I would like is to have the process start but have the input and output all be in the same console.
if(CreateProcessWithLogonW(user,domain, pass, LOGON_WITH_PROFILE, NULL, cmd, 0, 0, 0, &sa, &pe))
{
printf("[~] Process spawned with PID %X\n", pe.dwProcessId);
}
else
{
printf("[!] Failed to create process.... | According to help on this method:
The CREATE_DEFAULT_ERROR_MODE,
CREATE_NEW_CONSOLE, and
CREATE_NEW_PROCESS_GROUP flags are
enabled by default— even if you do not
set the flag, the system functions as
if it were set.
It looks like Windows API doesn't allow these flags not to be set.
|
1,551,085 | 1,551,116 | Standard practice for implementing threads in C++? | I'm looking forward to an interview in C++ in the coming weeks. (yay) So I have been relearning C++ and studying up. Unfortunately I have realized that I've never implemented threads in C++, and am somewhat concerned about a quiz on concurrency.
As far as I can tell, C++ uses pthreads in Linux and some other device in ... | Currently C++ is entirely unaware that threads exist. Different OSes provide threading libraries to make them available. The next version of C++, so called C++0x, is going to make a thread library standard. If I were to start a multithreaded app today I would go with either boost threads or the threads that were a pa... |
1,551,106 | 1,551,119 | How to use string and string pointers in C++ | I am very confused about when to use string (char) and when to use string pointers (char pointers) in C++. Here are two questions I'm having.
which one of the following two is correct?
string subString;
subString = anotherString.sub(9);
string *subString;
subString = &anotherString.sub(9);
which one of the following... | None of them are correct.
The member function sub does not exist for string, unless you are using another string class that is not std::string.
The second one of the first question subString = &anotherString.sub(9); is not safe, as you're storing the address of a temporary. It is also wrong as anotherString is a pointe... |
1,551,333 | 1,551,426 | Data structures for real time applications | We are designing a p2p applications using c++ which transmits voice to other peer using UDP.
We are capturing a mic signal in a buffer in the thread which captures voice for one second in the while loop. For every second voice captured in buffer it splits it into packets and sends to the other peer. Now I need a prope... | I would use boost::circular_buffer. You will get the cache benefits having a fixed memory area and no unexpected memory allocations.
In order to achieve maximum
efficiency, the circular_buffer stores
its elements in a contiguous region of
memory, which then enables:
Use of fixed memory and no implicit or
unex... |
1,551,408 | 1,551,412 | Help me debug this - invalid conversion from 'const char*' to 'char*' | I simply don't see why this error's popping up.
Widget.cpp: In constructor 'Widget::Widget(Generic, char*, int, int, int, QObject*)':
Widget.cpp:13: error: invalid conversion from 'const char*' to 'char*'
Nowhere do I have a 'const char*' in terms of Widget's constructor.
class Widget: public QObject {
Q_OBJECT
... | This is a const char * value
str.substr(pos1, pos2-pos1).c_str();
|
1,551,510 | 1,551,531 | return a list<int> from a function c++ | Every time I try to use my add function and return a list from it. I get an undefined symbol error. What am I doing wrong here.
this is the error:
Undefined first referenced
symbol in file
add(std::list<int, std::allocator<int> > const&, std::list<int, std::allocator<... | You used a $ instead of a & when you declared add() here...
list<int> add(const list<int> &lhs, const list<int> $rhs);
|
1,551,539 | 1,551,555 | What is the preferred design of a template function that requires a default parameter value? | I'm currently working on cleaning up an API full of function templates, and had a strong desire to write the following code.
template <typename T, typename U, typename V>
void doWork(const T& arg1, const U& arg2, V* optionalArg = 0);
When I invoke this template, I would like to do so as follows.
std::string text("hell... | I think that your forwarding function is a perfectly suitable solution, although in your solution, won't you have to explicitly specify the template parameters? (0 is an integer constant that can be coverted to any V* type.) Also doWord vs doWork?
As a general rule, try to avoid optional parameters where they don't hav... |
1,551,544 | 1,551,585 | Reading in image files without specifying name | Are there any facilities in SDL or C++ that allow you to read image files in from a folder without specifying their name, like reading them in sequential order, etc.? If not are there any techniques you use to accomplish something along the same lines?
Doing something like this:
foo_ani[0] = LoadImage("Animations/foo1.... | Use boost::filesystem.
The tiny program shown here lists all files in the directory files/, matching the pattern fileN.type, where N is from 0 and upwards, unspecified.
#include <iostream>
#include <sstream>
#include <string>
#include <boost/filesystem.hpp>
using namespace std;
namespace fs = boost::filesystem;
int ma... |
1,551,777 | 1,551,786 | Can the attributes of a class be an array? | I'm new to OOP, so please bear with me if this is a simple question. If I create a class, which has attributes "a", "b", and "c", is it possible for the attributes to be an array, such that attribute a[2] has a meaning?
| Member variables can ofcourse be arrays. Example:
class MyClass {
int a[3]; // Array containing three ints
int b;
int c;
};
|
1,551,829 | 1,551,852 | Can I delete a dynamically allocated class using a function within that class? | I'm writing a state manager for a game. I've got most of the logic down for how I want to do this.
I want states, which will be classes, to be handled in a stack in the StateManager class. Each state will have pause functions, and the stack will be an STL stack.
When a state is done with what it needs to do (example: f... | See C++-FAQ-lite: Is it legal (and moral) for a member function to say delete this?
As long as you're careful, it's OK for an object to commit suicide (delete this).
|
1,551,842 | 1,551,853 | Why are most of the biggest open source projects in C? | I'm having a debate with a friend and we're wondering why so many open source projects have decided to go with C instead of C++. Projects such as Apache, GTK, Gnome and more opted for C, but why not C++ since it's almost the same?
We're precisely looking for the reasons that would have led those projects (not only thos... | C is very portable, much more than C++ was 10 years ago.
Also, C is very entrenched in the Unix tradition. Read more in 'The Art of Unix Programming', about Unix and OO in general, and about specific languages on unix (including C and C++).
|
1,551,997 | 1,552,030 | How to disable visual C++ memory leak checking for a particular file? | One of my projects is making use of Microsoft's supplied memory leak checker via _CrtSetDbgFlag etc. This is working fine except that I now want to make use of a third-party package which is leaking a small amount of memory. I have no particular need to fix the leaks, but the output is annoying since it will disguise "... | You can deactive the heap allocation checker in the concerned files by use of _CrtSetDbgFlag() and the macro _CRTDBG_CHECK_DEFAULT_DF (which is equal to 0) before the first new instruction in a file where you don't want to check memory leaks and reactive it just after the new instructions. See MSDN here.
Another way on... |
1,552,058 | 1,552,104 | How to implement precompiled headers into your project | I understand the purpose and reasoning behind precompiled headers. However, what are the rules when implementing them? From my understanding, it goes something like this:
Set your project up to use precompiled headers with the YU directive.
Create your stdafx.h file and set that to be your precompiled header.
Includ... | You stdafx.cpp should include stdafx.h and be built using /Yc"stdafx.h".
Your other *.cpp should be include stdafx.h and be built using /Yu"stdafx.h".
Note the double-quote characters used in the compiler options!
Here's a screenshot of the Visual Studio settings for stdafx.cpp to create a precompiled header:
Here are... |
1,552,069 | 1,552,762 | Undefined reference to vtable. Trying to compile a Qt project | I'm using Code::Blocks 8.02 and the mingw 5.1.6 compiler. I'm getting this error when I compile my Qt project:
C:\Documents and Settings\The
Fuzz\Desktop\GUI\App_interface.cpp|33|undefined
reference to `vtable for AddressBook'
File AddressBook.h:
#ifndef ADDRESSBOOK_H
#define ADDRESSBOOK_H
#include <QWidget>
... | Warning: Do not do this if you already have a .pro file - you'll lose it!
In order to automatically ensure that all moc cpp files are generated, you can get qmake to automatically generate a .pro file for you instead of writing one yourself.
Run
qmake -project
in the project directory, and qmake will scan your directo... |
1,552,098 | 1,552,245 | ImpersonateLoggedOnUser doesn't appear to work | After a successful call to both LogonUser and ImpersonateLoggedOnUser it doesn't appear that my process is running as the new user...
system("whoami");
prints out:
Chris-PC\Chris
when it should be:
Chris-PC\LimitedGuy
Is there a function I'm not calling or something?
My code:
if(argc == 6) // impersonate
{
... | When you use the system call a new process is created to execute the command but in Windows the new process is always created with the token from the parent process not the thread (unless you specifically use one of the CreateProcessAsUser, CreateProcessWithLogonW, etc. calls). So in your case 'whoami' is executed in t... |
1,552,170 | 1,552,183 | Help with error: ISO C++ forbids declaration of 'vector' with no type | As the title states, I'm not sure why I'm getting this error. I've put together a test.cpp that's similar to this structure, and it works fine. Also, other than the vector problem, there's the other problem about 'protected', which isn't even in the code. I think 'protected' is a macro, so no telling what's there. I'm ... | Vector resides in the std namespace. You have to do one of the following:
Prepend the type with the namespace:
std::vector<std::vector<char *> > chars;
Tell the compiler you are using vector from the std namespace
using std::vector;
vector<vector<char *> > chars;
Or, tell the compiler you are using the std namespace,... |
1,552,354 | 1,552,365 | Problem overloading the < operator in C++ | I have a vector of Student objects which I want to sort using #include <algorithm> and sort(list.begin(), list.end());
In order to do this, I understand that I need to overload the "<" operator but after trying (and failing) with several methods suggested online, I am running out of ideas.
Here is my latest attempt:
In... | I wouldn't use a friend here, and I'm not sure it works at all. What I would use is...
class Student
{
public:
bool operator< (const Student& second) const;
};
bool Student::operator< (const Student& second) const
{
return (Name() < second.Name());
}
Note the trailing const, indicating that within operator<, ... |
1,552,495 | 1,552,513 | In C++, how do I push an object to a vector while maintaining a pointer to the object? | In my code, I have a vector of Student objects.
vector<Student> m_students;
I want to:
Check to see if the vector contains any Student of a certain name.
If no such Student exists, add a new one.
Add data to the Student of that name.
Consider the following code:
// Check to see if the Student already exists.
Student... | STL containers copy the objects they contain. There is no way to work around this.
You can, however, have a std::vector<std::shared_ptr<Student> >, which allow you to have a container of smart pointers. For this to work, though, your objects must all be attached to the shared_ptr at the time of construction.
So, someth... |
1,552,728 | 1,552,774 | Why can't the Nodes be linked together? | EDIT: Is it possible to NOT use new? (do not dynamically allocating memory)
I think it is push that is wrong, but I don't know where, how, and why. here is the code:
struct Node {
string fileName;
Node *link;
};
int size(Node *&flist) {
int count = 0;
Node *tempPtr = flist;
while (tempPtr != 0) {
... | In your size() function you are modifying the list in the loop. You don't want to modify tempPtr->link but rather just change tempPtr as you iterate. Changing tempPtr won't modify anything permanently. You should also avoid passing flist by reference here as there's no need to modify it. So:
int size(Node *flist) {
... |
1,552,738 | 3,946,294 | Is there a Java equivalent of frexp? | Is there a Java equivalent of the C / C++ function called frexp? If you aren't familiar, frexp is defined by Wikipedia to "break floating-point number down into mantissa and exponent."
I am looking for an implementation with both speed and accuracy but I would rather have the accuracy if I could only choose one.
This ... | How's this?
public static class FRexpResult
{
public int exponent = 0;
public double mantissa = 0.;
}
public static FRexpResult frexp(double value)
{
final FRexpResult result = new FRexpResult();
long bits = Double.doubleToLongBits(value);
double realMant = 1.;
// Test for NaN, infinity, and zero.
... |
1,552,787 | 1,552,864 | compare dates in C++ | i have a file, 'date.txt' which has date in it. Like,
Mon Oct 13 09:37:08 2009.
Now i want to compare this date with system date. How can i compare dates in C++.?
I used this code to get the contents from the file 'date.txt'
string date;
while ( inDateFile >>date) //inDateFile is an ifstream object
... | Parse values, use std::mktime function to get time_t and now use std::difftime to get the difference.
|
1,553,382 | 1,553,407 | Is delete[] equal to delete? | IP_ADAPTER_INFO *ptr=new IP_ADAPTER_INFO[100];
if I free using
delete ptr;
will it lead to memory leak, if not then why ?
This is disassembly code generated by VS2005
; delete ptr;
0041351D mov eax,dword ptr [ptr]
00413520 mov dword ptr [ebp-0ECh],eax
00413526 mov ecx,dword ptr [ebp-0ECh... | Whether this leads to a memory leak, wipes your hard disk, gets you pregnant, makes nasty Nasal Demons chasing you around your apartment, or lets everything work fine with no apparent problems, is undefined. It might be this way with one compiler, and change with another, change with a new compiler version, with each n... |
1,553,435 | 1,553,529 | tcmalloc: how can I get my malloc calls overridden when compiling statically? | When I use LD_PRELOAD=/usr/local/lib/libtcmalloc.so, all my calls to malloc become tcmalloc calls. However, when I link statically against libtcmalloc, I find that straight malloc is getting called unless I still use the LD_PRELOAD setting.
So how can I statically compile against tcmalloc in such a way that my mallocs... | Symbols are resolved on a first match basis. You need to make sure that libtcmalloc.a is searched before libc.a by the linker. I assume that you are not explicitly linking libc.a since you do not normally need to do so. The solution is to specify -nostdlibs, and then explicitly link all necessary libraries in the order... |
1,553,603 | 1,553,915 | How to know if a given DLL is loaded by a given process? |
Possible Duplicate:
How to programmatically get DLL dependencies
On Windows, in a C++ program, I want to know if a given DLL (I know the path) is loaded by a given external process (I know the path of the exe), using win32 functions.
It must be possible to list all DLLs loaded by a process, as process explorer does.... | First you have get the ID of the Process you are looking for. Use the EnumProcesses function described here to find your desired process. There is a nice example provided to list all processes and their names, that you can use as a starting point.
As the second step you can list all of the modules, that is the DLLs loa... |
1,553,817 | 1,553,943 | C++ Read from shared memory | I want to read status information that an application provides via shared memory. I want to use C++ in order to read the content of that named shared memory and then call it with pinvoke from a C#-class.
From the software I know that it has a certain file structure: A struct STATUS_DATA with an array of four structs of... | The last parameter to MapViewOfFile (dwNumberOfBytesToMap) must be less than the maximum size specified when the mapping was created. Since we don't know what that size is, it seems fair to assume that BUF_SIZE is exceeding it and 1024 isn't. Specifying 0 for this parameter is an easy way to map the entire file into a ... |
1,553,854 | 1,553,875 | Template static variable | I can't understand, why if we define static variable of usual (non-template) class in header, we have linker error, but in case of templates all works fine and moreover we will have single instance of static variable among all translation units:
It's template header (template.h):
// template.h
template<typename T>
clas... | It's because the definition of the static data member is itself a template. Allowing this is necessary for the same reason you are allowed to have a function template that's not inline multiple times in a program. You need the template to generate the resulting entity (say, a function, or a static data member). If you ... |
1,553,914 | 1,553,942 | New keywords and new type of pointers in Visual C++ 2005. What is managed C++? |
Possible duplicates
What is gcnew?
What does the caret mean in C++/CLI?
Difference between managed c++ and c++
I am a advanced C++ programmer with g++. But currently I am working on Visual C++ 2005 doing Windows Forms Application programming . But I am finding it hard with its new terminology. For e.g. instead of new... | The gcnew and ^ values are managed C++ which is a different language to c++. You can use VS2005 as a normal C++ compiler by not using a project type from the CLR section of the new project window.
|
1,554,047 | 1,554,405 | Convert a C++ program to a Windows service? | I've written a console program that "does stuff" - mainly using boost. How do I convert it to a Windows Service?
What should I know about Windows Services beforehand?
| There's a good example on how to set up a minimal service on MSDN. See the parts about writing the main function, entry point and also the example code.
Once you've got a windows service built and running, you'll discover the next major gotcha: it's a pain to debug. There's no terminal (and hence no stdout/stderr) and... |
1,554,070 | 1,554,137 | How to retrieve FQDN of the current host on Win32? | What's an easiest reliable way to retrieve the fully qualified domain name of the current host in Win32?
I've tried calling gethostname(), but it returns a NetBIOS name.
| Try getnameinfo, it comes with a sample that worked for me.
|
1,554,083 | 1,815,221 | QT4 incomplete getting website content | I'm trying to write a small test using QHttp to get an URL and return its content.
The program ran fine, but it has some problem.
With this link http://www.mediafire.com/download.php?ztyniqhd4lb ( or some random MF link ), my program cannot load all its content.
With some workaround, I found that all the SIGNAL before... | I was about to say that QHttp is deprecated. You should use QNetworkAccessManager.
|
1,554,276 | 1,588,619 | How can I define operations on a template without caring what type it's instantiated with? | I have inherited a bunch of networking code that defined numerous packet types. I have to write a bunch of conversion functions that take structs of a certain type, and copy the values into other structs that have the same fields, but in a different order (as part of a convoluted partial platform bit order conversion ... | I ended up doing something like what outis suggested in the comment on the original question. First, I created an unspecialized conversion class template, like so:
template <class type_1>
struct conversion {};
I then threw in a macro for specializing this class (which I believe is like the traits template outis sugge... |
1,554,558 | 1,554,614 | Best way to create an Environment object in C++ | I want to create an environment class that is accessible from all of my classes in my program but I dont want to initialize the environment object everytime I want to access its members from my other classes. What is the best way to go around doing this in C++?
I want to do this because I have the environment object st... | A Singleton object isn't always the solution. While sometimes it seems like an easy solution, it does have some disadvantages (see this question for example).
How many of your classes actually need access to this Environment object? If you literally meant that every class you have do then it sounds like your design is ... |
1,554,591 | 1,554,621 | How to start a process on a remote machine in C++ under Windows | I'm using Dev-C++ under Windows. My question is how can i start a process on a remote machine? I know that PsExec can do that, but if it's possible, i want to avoid to use it.
If someone can give some example code, i would appreciate it :)
Thanks in advance!
kampi
| If this was easy, hackers would be starting up malware on all machines exposed to the internet.
PSExec uses the Services Control Manager over a LAN to start a service EXE from 'here', i.e. the machine where you run it. It requires a lot of security privileges - e.g. admin rights.
If you don't want to do this, you can l... |
1,554,750 | 1,554,822 | C++ const keyword - use liberally? | In the following C++ functions:
void MyFunction(int age, House &purchased_house)
{
...
}
void MyFunction(const int age, House &purchased_house)
{
...
}
Which is better?
In both, 'age' is passed by value. I am wondering if the 'const' keyword is necessary: It seems redundant to me, but also helpful (as an ext... | This, IMHO, is overusing.
When you say 'const int age,...' what you actually say is "you can't change even the local copy inside your function". What you do is actually make the programmer code less readable by forcing him to use another local copy when he wants to change age/pass it by non-const reference.
Any progr... |
1,554,774 | 1,554,796 | Create new C++ object at specific memory address? | Is it possible in C++ to create a new object at a specific memory location? I have a block of shared memory in which I would like to create an object. Is this possible?
| You want placement new(). It basically calls the constructor using a block of existing memory instead of allocating new memory from the heap.
Edit: make sure that you understand the note about being responsible for calling the destructor explicitly for objects created using placement new() before you use it!
|
1,554,878 | 1,589,326 | Why does Windows not allow WinSock to be started while impersonating another user | Using my own program or others I can't get winsock to run when calling if the process is created with CreateProcessWithLogonW or CreateProcessAsUserW. It returns this error when I create the socket:
WSAEPROVIDERFAILEDINIT 10106
Service provider failed to initialize.
The requested service provider could not be loaded... | You have to have the Act As Operating Priv
|
1,554,910 | 1,555,046 | D.R.Y vs "avoid macros" | I am creating my own implementation of XUL in C++ using the Windows API. The fact that the elements are constructed by the XML parser requires that they have identical interfaces, so that we don't need to write custom code for each element constructor. The result is that most of my elements look like this:
class Button... | I would not use a macro here. The clue is in your class "Description", which has an extra member function init, which the others don't. So you wouldn't be able to use the macro to define it, but you'd instead expand the macro manually and add the extra line.
To me, this is a bigger violation of DRY than just writing ou... |
1,554,984 | 1,562,458 | C++: LINK : debug\XXXXX.exe not found or not built by the last incremental link; performing full link | Using visual studio 2008 SP1,
This line:
LINK : debug\XXXXX.exe not found or not built by the last incremental link; performing full link
appears every single time I compile the project, no matter how small a change I make.
What could be the reasons for that?
| So it turns out that the problem fixes it self if I add /INCREMENTAL to the linker command line. This in spite the fact that the default behavior according to the docs is to enable incremental linking.
Strange.
|
1,555,368 | 1,555,404 | C++ char** -> vector<string> -> string -> char** parsing problem | Lets say that I'm trying to solve a parsing problem of string to char **
For some reason the below code generates a lot of trash, can anyone have a look at it please?
Here's what it's supposed to do :
Dump all argv into a string_array
container
Dump everything in the string_array
container into a std::string and
separ... | C-style strings (char*) are meant to be zero-terminated. So instead of new char[tokens[i].size()], you need to add 1 to the allocation: new char[token[i].size() + 1]. Also, you need to set new_args[i][tokens[i].size()] = 0 to zero-terminate the string.
Without the zero-terminator, programs would not know when to stop p... |
1,555,545 | 1,555,621 | Const Correctness Question in C++ | I have a random question about const correctness.
Lets say i have a class that is a singleton.
class Foo : public Singleton<Foo>
{
friend class Singleton<Foo>;
public:
std::wstring GetOrSet(const int id) const;
private:
Foo();
~Foo();
void LoadStringIntoMap(const int id, const std::wstring &msg);
... | GetInstance() returns a non-const pointer.
As the function GetInstance() is not bound to the object itself, but class-wide, it may be called from a const function.
Essentially, you have tricked yourself out of the const environment; but then, you could do that from any context/state of your program (privateness of memb... |
1,555,548 | 1,555,670 | VB6 GUI not working in multithreaded COM environment | I have a VB6 COM client that makes calls to an inprocess STA ATL/COM server. One of the Server methods, X, can take a while to finish so I need to be able to cancel it. What I tried was to run the method code in a new thread and include another method, Y, that does a timed WaitForSinleObject. So the client first calls ... | You should always marshal your connection-point calls. When you don't do that, you can call VB code, but it fails in random ways (non-marshaled-objects), or just doesn't work (GUI).
To use marshaling, you have to implement several interfaces (see below).
The other possibility is to convert the asynchronous calls to VB ... |
1,555,640 | 1,555,710 | Which is latest C++ Standard Release , From where i can download it |
Possible Duplicate:
Where do I find the current {X} standard?
I have a simple Question !
I am looking for soft copy of latest C++ Standard release. I have ISO/IEC 14882 First Edition ,1998-09-01, But i have doubt if it is latest.
I visited http://www.open-std.org/jtc1/sc22/wg21/, There are many drafts.
Please guid... | If you don't want to pay money, you can always use the final draft. It is basically the same with only minor edits. And it is free.
You can find a PDF here. Otherwise just search for 14882 final draft.
edit: Updated link to the document instead of the index
|
1,555,661 | 1,555,728 | Initializing an array in C++ | I am trying to initialize an array of objects:
SinglyLinkedList offeredClasses[22] = {SinglyLinkedList("CSCE101"),SinglyLinkedList("CSCE101L"),SinglyLinkedList("CSCE150E"),SinglyLinkedList("CSCE150EL"),SinglyLinkedList("CSCE150EM"),SinglyLinkedList("CSCE150EML"),SinglyLinkedList("CSCE155"),SinglyLinkedList("CSCE155H"),... | It appears theat your compiler is seriously broken. Your copy-constructor is declared with a non-const reference parameter. Such a copy-constructor cannot be invoked with temporary object as an argument, since a non-const reference cannot be bound to a temporary object.
Your initializers are temporary objects, meaning... |
1,555,719 | 1,555,725 | C++ c_str doesn't return entire string | I've tried the following code with both normal ifstreams and the current boost:iostream I'm using, both have the same result.
It is intended to load a file from physfs into memory then pass it to a handler to process (eg Image, audio or data). Currently when c_str is called it only returns a small part of the file.
... | I imagine that the next character is a null (ASCII 0) byte. c_str() simply gives you a *char, therefore your write to stdout is interpreted as a class C string which ends at the first null byte.
If you really need a C-like interface to this string, the main thing is that theFile->c_str() points to your data and theFile... |
1,555,825 | 1,555,987 | I'm an experienced C# developer, what things should I know to code effectively in c/c++? | I have a little bit of experience in c/c++ from college but have not worked in it for years. What sorts of things do I need to know to even be considered for a c/c++ job position?
| I have to disagree with a lot of the advice you've received. You should not concentrate on manual memory management. Manual memory management was/is difficult to avoid in C. Most C++ code, however, has little need to use manual memory management at all. Manual memory management is heavily overused in a great deal of co... |
1,556,014 | 1,556,024 | Memory usage isn't decreasing when using free? | Somehow this call to free() is not working. I ran this application on Windows and followed the memory using in Task Manager, but saw no reduction in memory usage after the call to free().
int main(int argc, char *argv[])
{
int i=0;
int *ptr;
ptr = (int*) malloc(sizeof(int) * 1000);
for (i=0; i < 1000;... | Typical C implementations do not return free:d memory to the operating system. It is available for use by the same program, but not to others.
|
1,556,054 | 1,738,280 | Problem between a QTcpServer and a TCPClientSocket (Cayuga) | I try to communicate via TCP Socket between a QT4-Application (MyApp) and Cayuga (written in C++).
The connection part works fine, i.e. Cayuga connects to MyApp.
Now, MyApp is sending some data to Cayuga, but nothing is received.
void MyApp::init()
QTcpServer *m_server;
QTcpSocket *clientConnection;
//Open socket for... | This is my guess of what's happening:
QDataStream implements a serializing protocol (Hence having to specify a version (Qt_4_0) for it). You need something on the other end that understands that protocol (to wit, another Qt_4_0 DataStream). Particularly, QDataStream makes sure you get the right data regardless of the e... |
1,556,150 | 1,556,338 | deleting char ** correctly? | I've created a 2d array of c-strings using :
char ** my_array = new char*[N];
and then I initialized each row using :
my_array[i] = new char[M]; // where M is a varying number. assign values to my_array[i] later
So I pretty much got a jagged 2d array.
I wanted to proceed and delete the whole thing like this :
for(int... | In your array initialization code you allocate 'tokens[i].size()' characters for each 'tokens[i]' element, and then you initialize elements from 0 to 'tokens[i].size()'. This is obvious memory overrun. If you want to have elements from 0 to 'tokens[i].size()', you need to allocate an array of size 'tokens[i].size() + 1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.