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
2,189,245
2,189,263
How can I get the username of the person executing my program?
How can I get the username of the process owner (the user who is executing my program) in C++?
Windows GetUserName() Example: char user_name[UNLEN+1]; DWORD user_name_size = sizeof(user_name); if (GetUserName(user_name, &user_name_size)) cout << "Your user name is: " << user_name << endl; else /* Handle error */ Linux Look at getpwuid: The getpwuid() function shall search the user database for...
2,189,279
2,189,632
implicit promotion to avoid overflow in std::partial_sum
This code suffers from overflow because the type of intermediate results does not depend on the destination type: vector< uint8_t > increments; … vector< uint32_t > increasing( increments.size() ); partial_sum( increments.begin(), increments.end(), increasing.begin() ); However, so does this (GCC 4.2): partial_sum( in...
According to http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#539, partial_sum has been completely redefined since n3000 (the latest release): Effects: Let VT be InputIterator's value type. For a nonempty range, initializes an accumulator acc of type VT with *first and performs *result = acc. For e...
2,189,304
2,189,375
How to check open processes in C++?
In Windows I would like the C++ command or reference that would get the "tasklist" in C++ and output it to a buffer?
Use EnumProcesses() to get the process identifiers, use OpenProcess() to get their handles and get the information you need via the usual process functions.
2,189,430
2,189,444
How to port forward in C++?
I have a sockets program that requires port 1002 to be open and I wanna know how to port forward in C++ on windows so i may use this port freely?
Port forwarding is done upstream of the client system, typically on the router. I believe some applications use Universal Plug and Play to communicate with the upstream router to open a port publicly but you'll have to do a lot of research to see how it's done: I haven't the slightest.
2,189,577
2,189,680
Simple File I/O in C++ - Never Exits This Loop?
I'm a programming student in my second OOP class, my first class was taught in C# and this class is taught in C++. To get our feet wet in C++, our professor has asked us to write a rather large program with File I/O. The problem is, I have a small part of my program that is not working, at least, not for me. The projec...
I don't know what input you are giving to cin, but be aware that cin will stop at the first whitespace character it encounters. For example, if you give as input the following: C:\Program Files\directory then aRDataLog would have the value C:\Program . In order to read the whole line, you could use getline. Check also...
2,189,616
2,189,620
Should I use a function in a situation where it would be called an extreme number of times?
I have a section of my program that contains a large amount of math with some rather long equations. Its long and unsightly and I wish to replace it with a function. However, chunk of code is used an extreme number of times in my code and also requires a lot of variables to be initialized. If I'm worried about speed, ...
Most compilers are smart about inlining reasonably small functions to avoid the overhead of a function call. For functions big enough that the compiler won't inline them, the overhead for the call is probably a very small fraction of the total execution time. Check your compiler documentation to understand it's specif...
2,189,723
2,189,763
Double to int conversion behind the scene?
I am just curious to know what happens behind the scene to convert a double to int, say int(5666.1) ? Is that going to be more expensive than a static_cast of a child class to parent? Since the representation of the int and double are fundamentally different is there going to be temporaries created during the process a...
Any CPU with native floating point will have an instruction to convert floating-point to integer data. That operation can take from a few cycles to many. Usually there are separate CPU registers for FP and integers, so you also have to subsequently move the integer to an integer register before you can use it. That may...
2,189,780
2,189,807
Can all keys be represented as a single char in c++?
I've searched around and I can't seem to find a way to represent arrow keys or the escape key as single char in c++. Is this even possible? I would expect that it would be similar to \t or \n for tab and new line respectively. Whenever I search for escaped characters, there's only ever a list of five or six well know...
The short answer is no. The long answer is that there are a number of control characters in the standard ANSI character set (from decimal 1 to decimal 31, inclusive), among which are the control codes for linefeed, carriage return, end-of-file, and so on. A few are commonly interpreted as arrows and the escape key, but...
2,189,883
2,189,895
C++ STL Memory Allocator Compile Error
I'm writing a C++ custom allocator for use with STL. When I put the following code in the class definition, it compiles: #include "MyAlloc.hpp" #if 1 template <typename T> typename MyAlloc<T>::pointer MyAlloc<T>::allocate(size_type n, MyAlloc<void>::const_pointer p) { void *ptr = getMemory(n*sizeof(T)); typename ...
Templates must always be defined within a translation unit. In order to use the template function, the definition of the template needs to go in the header file, not a separate .cpp file.
2,190,026
2,190,047
Where is pointer metadata stored?
Could be that I am overlooking something obvious, but where is pointer metadata stored? For instance if I have a 32-bit int pointer ptr and I execute ptr++ it knows to advance 4 bytes in memory. However, if I have a 64-bit int pointer it knows to advance 8 bytes. So who keeps track of what type of pointer ptr is and wh...
It isn't stored anywhere, per-se. The compiler looks at the type of the ptr and turns the ++ operation into an increment of the correct number of bytes.
2,190,080
2,190,145
Using boost::random and getting same sequence of numbers
I have the following code: Class B { void generator() { // creating random number generator boost::mt19937 randgen(static_cast<unsigned int>(std::time(0))); boost::normal_distribution<float> noise(0,1); boost::variate_generator<boost::mt19937, boost::normal_distribution<float> > nD(randgen, no...
One way would be to not reseed the random number generator every time you execute your code. Create the generator and seed it once, then just continue to use it. That's assuming you're calling that code multiple times within the same run. If you're doing multiple runs (but still within the same second), you can use an...
2,190,231
2,190,552
Looking for a C or C++ library providing a functionality similar to Google Go's channels
...for use in a multithreaded network server. I want to pass data around between multiple threads. Currently I'm using sockets, with the master thread blocking on select() and workers blocking on recv(), though I feel there probably are more advanced or prepackaged ways of handling this task in C++.
I would have worker threads waiting in a thread pool. Then the master waiting on select (for both reads and writes). As data comes the master adds jobs to the thread pool. As each job is added a thread wakes up executes the job and returns to the pool. This way you are not blocking threads waiting on specific ports w...
2,190,349
2,191,360
None in boost.python
I am trying to translate the following code d = {} d[0] = None into C++ with boost.python boost::python::dict d; d[0] = ?None How can I get a None object in boost.python?
There is no constructor of boost::python::object that takes a PyObject* (from my understanding, a ctor like that would invalidate the whole idea if mapping Python types to C++ types anyway, because the PyObject* could be anything). According to the documentation: object(); Effects: Constructs an object managing a refe...
2,190,416
2,190,971
What does C4250 VC++ warning mean?
What does C4250 Visual C+ warning mean in practical terms? I've read the linked MSDN page, but I still don't get what the problem is. What does the compiler warn me about and what problems could arise if I ignore the warning?
The warning is pointing out that if any weak class operations depend on vbc virtual operations that are implemented in dominant, then those operations might change behavior due to the fact that they are bundled in a diamond inheritance hierarchy. struct base { virtual int number() { return 0; } }; struct weak : pub...
2,190,444
2,190,454
Operators in C/C++/Java
Consider the following fragment: int a,b; a = 1; b = 2; c = a++++b; // does not work!! Compilation error. c = a++*+b; // works !! Help me understand this behaviour.
c = a++++b; is treated as: c = ((a++)++)b; which is incorrect as you are trying to increment non-lvalue. and c = a++*+b; is treated as: c = (a++)*(+b); The cause for this behaviour is: The C language lexical analyzer is greedy. In case 1: After the token 'a' (identifier) the lexer sees +, followed by another +...
2,190,455
2,190,629
Why we can't implement polymorphism in C++ without base class pointer or reference?
First of all have a look at the following code (in this code shape is the base class and line is the derived class) void drawshapes(shape sarray[],int size) { for(int i=0;i< size; i++) sarray[i].draw(); } main() { line larray[10]; larray[0]=line(p1,p2);//assuming that we have a point class larra...
You are asking a question and providing a code example that fails but for a different reason. From the wording of your question: Why are references/pointers required for polymorphism? struct base { virtual void f(); }; struct derived : public base { virtual void f(); }; void call1( base b ) { b.f(); // base::f...
2,190,463
2,190,489
An interview question
Given a linked list of T size , select first 2n nodes and delete first n nodes from them; Then do it for the next 2n nodes and so on... For example- Let's consider a linked list of size 7: `1->2->3->4->5->6->7` If n = 2, the desired output is : `1->2->5->6->7` I didn't understand what this problem is actually in...
That actually looks like it should say: Given a linked list of T size , select first 2n nodes and delete last n nodes from them; Then do it for the next 2n nodes and so on... or: Given a linked list of T size , select first 2n nodes and keep first n nodes from them; Then do it for the next 2n nodes and so on... Tha...
2,190,504
2,190,512
Difference between intellisense and compiler in VS.NET C++ 2010
Is the following legal C++ code: class C { static public int x; }; It compiles OK in Visual Studio 2008 C++ and Visual Studio 2010 C++ (beta 2). But the static member x does not end up being public. In Visual Studio 2010 beta 2 the experience is even stranger. Intellisense reports an error "expected an identif...
This is not legal C++. It is a legal C#, so that's why MS IDE bugged out. Correct: public: static int x;
2,190,695
2,190,726
Problem passing vector of templated states to constructor
For those who are following the saga, I am still trying to define Finite State Machine, states & events in the "proper" C++ way, with templates. What's wrong with this code? template <typename StateTypeEnum, typename EventTypeEnum> class Fsm { public: Fsm(E_subSystems subSystem, uint8_t instance, ...
The problem is not in the code you present, but most probably a member of type State that is not being initialized in the initialization list of some constructor, forcing the compiler to default initialize it, and the compiler is not finding the appropriate constructor. I can only assume that line 98 is in the Fsm cons...
2,190,919
2,190,981
Mixing extern and const
Can I mix extern and const, as extern const? If yes, does the const qualifier impose it's reign only within the scope it's declared in or should it exactly match the declaration of the translational unit it's declared in? I.e. can I declare say extern const int i; even when the actual i is not a const and vice versa?
Yes, you can use them together. And yes, it should exactly match the declaration in the translation unit it's actually declared in. Unless of course you are participating in the Underhanded C Programming Contest :-) The usual pattern is: file.h: extern const int a_global_var; file.c: #include "file.h" const int ...
2,190,993
2,191,072
Creating an ATL COM object that implements a specific interface
I need to implement a simple ATL COM object that implements a specific interface for which I have been given both a .tlb file and a .idl file. The interface is very simple and only consists of a single method. I have created many ATL objects in the past but never one that has to implement a specific interface. What ...
It's much more automatic than the other answers here are suggesting. All the boilerplate code is written for you by Visual Studio. You're lucky you have the .idl, it's by far the most conveninent, I think. You could paste the contents of the .idl file into your ATL COM project's existing .idl file, which would give you...
2,191,076
2,191,125
Explicitly passing a const object to an constructor which takes const reference to a polymorphic class
I got into a problem with my classes, passing a const object (polymorphic structure) to an explicit constructor which takes a const reference to the base class of that polymorphic structure. Here is the sample (this is not from my code, it is for explanation here) class Base { ... } class Derived:public Base { ... } ...
The problem is you aren't declaring an object, but a function: Problem no3(Derived()); // equivalent to: Problem no3(Derived); // with parameter name omitted Use: Problem no3((Derived())); // extra parens prevent function-declaration interpretation // which is otherwise required by the standard (so that the code isn't...
2,191,146
2,191,170
XML usage for c++ application
I have a couple of questions about XML. Can XML be used for normal c++ application instead of using a text file ? If so, does this method have advantages? and finally, how can I use XML to store data? what tools are needed? Regards.
You can use XML for storing information - it's less Human readable than a text file, but can be more easily communicated with other systems and coding languages. If all you need is a few text/numeric properties, stick to a property file. If you need a mix of configuration options, and you want to use validation (can be...
2,191,168
2,193,571
Mac OS. How to create image from PNG data?
I have an array of data that represents PNG: unsigned short systemFontTexture[] = { ... 0x5089,0x474E,0x0A0D,0x5089,0x474E,0x0A0D,0x5089, 0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089, 0x474E,0x0A0D,0x5089,0x474E,0x474E,0x0A0D,0x5089, ... } Can I create PNG file using this data? If yes, then HOW?
Create a data provider to serve up the data, and then create an image with the data provider.
2,191,238
2,191,267
How to allow your data structure to take in objects of any class - C++
How do I do that? Like you know in Java, you can use an ArrayList and it will take any object as long as you cast it down to whatever it is when you're retrieving the object. Even better, you can specify what class of objects that ArrayList would store by doing... new ArrayList()< whateverObject > I've implemented a ...
Templates are the answer to your question. Define your linked list as follows : template<typename ItemType> class ArrayList { // What's inside your class definition does not need to be changed // Include your method definitions here and you'll be fine }; The type to use is then ArrayList<WhateverObject>.
2,191,572
2,192,290
Iterator for custom container with derived classes
I've a custom container which is implemented in two different ways, but with a single interface. some thing like this. class Vector { virtual Iterator begin() = 0; virtual Iterator end () = 0 ; ... // some more functions. } ; class VectorImplA : public Vector { Iterator b...
I've run into exactly this problem myself before. While there are ways to solve your problem, you most likely should let go of the idea of a vector base class. What you probably should do instead, is mimic the way the c++ STL container are designed. The STL consists of concepts rather than base classes. An std::vector ...
2,191,684
2,191,928
How to write a GUI for a large cross-platform C++ project?
I have a large cross-platform (Linux and Windows) C++ project, for which I want to create a GUI. I have few very general questions about the basic principles of GUI for such project: Should the GUI be separated from the application's logic? If it is separated, how should the logic and the GUI communicate? Are TCP/IP s...
Should the GUI be separated from the application's logic? Yes, definitely.... If it is separated, how should the logic and the GUI communicate? Are TCP/IP sockets a good option? What are other possibilities? ...but not that much. Sockets would be overkill (exception: see question 5). Usually you split up the classes i...
2,191,724
2,192,608
Using Iterators to hide internal container and achieve generic operation over a base container
I basically want to have a base container class which can return a generic iterator that can be used to traverse an instance of the container class, without needing to specify iterator templates. I think I cannot implement the base container over a class template, which would then require a traversal algorithm based on...
It's gonna be complicated. As already stated, first you need your iterators to have value semantic because since they are usually copied around otherwise it would result in object slicing. class BaseContainer { protected: class BaseIteratorImpl; // Abstract class, for the interface public: class iterator { pub...
2,191,782
2,191,797
Differences between structs and classes?
Do structures support inheritance? I think it's stupid question, but I have not much idea about it. What is the meaning of writing code like this: struct A { void f() { cout << "Class A" << endl; } }; struct B: A { void f() { cout << "Class B" << endl; } }; In structures also private section will come, don't th...
Yes structures support all features that classes do. The differences are: structure inheritance is public by default structure members are public by default
2,191,831
2,191,846
Real time plotting/data logging
I'm going to write a program that plots data from a sensor connected to the computer. The sensor value is going to be plotted as a function of the time (sensor value on the y-axis, time on the x-axis). I want to be able to add new values to the plot in real time. What would be best to do this with in C++? Edit: And by ...
Write a function that can plot a std::deque in a way you like, then .push_back() values from the sensor onto the queue as they come available, and .pop_front() values from the queue if it becomes too long for nice plotting. The exact nature of your plotting function depends on your platform, needs, sense of esthetics, ...
2,192,086
2,192,151
Which one is faster, reading from disk or allocate system memory
My environment is XP 32-bit. I find when allocated memory is nearly the maximum size, 2GB, that means a little virtual space is available, allocationnew memory is very slow. So if I have a page file, my app need to analyze them. I have two ways. One is to read them all into system memory, then do the analysis. The ot...
(1) I'm not sure the question matches the title. If you're allocating close to 2GB of RAM on 32 bit Windows, the system is probably paging a lot of memory to disk, and that's where I'd look first for the slow down. When you're using a lot of memory, you should think of it as being stored on disk (in pagefile.sys) but c...
2,192,238
2,192,255
What are the differences in string initialization in C++?
Is there any difference between std::string s1("foo"); and std::string s2 = "foo"; ?
Yes and No. The first is initialized explicitly, and the second is copy initialized. The standards permits to replace the second with the first. In practice, the produced code is the same. Here is what happens in a nutshell: std::string s1("foo"); The string constructor of the form: string ( const char * s ); is call...
2,192,253
2,192,261
Can two booleans be compared in C++?
Is the following piece of code supposed to work? bool b1 = true; bool b2 = 1 < 2; if (b1 == b2) { // do something } I suspect that not all 'trues' are equal.
Yes. All trues are equal.
2,192,326
2,192,383
To get reference counting, do I have to clutter my APIs with shared_ptr?
I recently had the following memory bug, which is easy to spot here, but can be harder to detect in more complex code: class Foo : public IFoo { const Bar& bar_; public: Foo(const Bar& bar) : bar_(bar) { } void test() { // access bar_ here } }; int baz() { IFoo* foo = NULL; if(whatever) { Bar bar...
Actually I do use shared_ptr everywhere... There are several ways to make it look less cluttered. One convention I use is typedefs for each defined class: class AClass { public: typedef boost::shared_ptr<AClass> Ptr; typedef boost::weak_ptr<AClass> Ref; //... }; Makes the code much more readable :) As for ...
2,192,415
2,192,460
unlink vs remove in c++
What is the difference between remove and unlink functions in C++?
Apart from the fact that unlink is unix-specific (as pointed out by Chris), we read in the POSIX manual: If path does not name a directory, remove(path) is equivalent to unlink(path). If path names a directory, remove(path) is equivalent to rmdir(path). As for the directory-passed unlink, we read: The path argumen...
2,192,416
2,192,903
How to convert concatenated strings to wide-char with the C preprocessor?
I am working on a project where I have many constant strings formed by concatenation (numbers, etc.). For example, I have a LOCATION macro that formats __FILE__ and __LINE__ into a string that I can use to know where I am in the code, when printing messages or errors: #define _STR(x) # x #define STR(x) _STR(x) #...
According to the C standard (aka "ISO-9899:1999" aka "C99"), Visual C is wrong and gcc is correct. That standard states, section 6.4.5/4: In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and wide string literal tokens are concatenated into a single multibyte char...
2,192,476
2,287,878
Thread Building Block versus MPI, which one fits mt need better?
Now I have a serial solver in C++ for solving optimization problems and I am supposed to parallelize my solver with different parameters to see whether it can help improve the performance of the solver. Now I am not sure whther I should use TBB or MPI. From a TBB book I read, I feel TBB is more suitable for looping or...
The basic thing you need to have in mind is to choose between shared-memory and distributed-memory. Shared-memory is when you have more than one process (normally more than one thread within a process) that can access a common memory. This can be quite fine-grained and it is normally simpler to adapt a single-threaded...
2,192,584
2,424,273
How do I decrypt a file with Crypto++ that was encrypted with C#
I would like to decrypt a file that I previously encrypted with C# using the TripleDESCryptoServiceProvider. Here's my code for encrypting: private static void EncryptData(MemoryStream streamToEncrypt) { // initialize the encryption algorithm TripleDES algorithm = new TripleDESCryptoServiceProvider(...
I managed to do that task with Windows Crypto API as stated in my other post.
2,192,680
2,192,771
Macro / keyword which can be used to print out method name?
__FILE__ and __LINE__ are well known. There is a __func__ since C99. #include <iostream> struct Foo { void Do(){ std::cout << __func__ << std::endl; } }; int main() { std::cout << __func__ << std::endl; Foo foo; foo.Do(); return 0; } will output main Do Is there any macro / keyword th...
Boost has a special utility macro called BOOST_CURRENT_FUNCTION that hides the differences between the compiler implementations. Following it's implementation we see that there are several macros depending on compiler: __PRETTY_FUNCTION__ -- GCC, MetroWerks, Digital Mars, ICC, MinGW __FUNCSIG__ -- MSVC __FUNCTION__ --...
2,192,880
2,192,994
Worst side effects from chars signedness. (Explanation of signedness effects on chars and casts)
I frequently work with libraries that use char when working with bytes in C++. The alternative is to define a "Byte" as unsigned char but that not the standard they decided to use. I frequently pass bytes from C# into the C++ dlls and cast them to char to work with the library. When casting ints to chars or chars to ot...
One major risk is if you need to shift the bytes. A signed char keeps the sign-bit when right-shifted, whereas an unsigned char doesn't. Here's a small test program: #include <stdio.h> int main (void) { signed char a = -1; unsigned char b = 255; printf("%d\n%d\n", a >> 1, b >> 1); return 0; } It sho...
2,192,902
2,195,659
Why this Dijkstra (graph) implementation isn't working?
I made this implementation for this problem : http://www.spoj.pl/problems/SHOP/ #include<iostream> #include<stdio.h> #include<queue> #include<conio.h> #include<string.h> using namespace std; struct node { int x; int y; int time; }; bool operator <(const node &s,const node &r) { if(s.time>r.time) r...
First of all, the graph parsing code is incorrect. The first line specifies width and height, where the width is the number of characters per line the height is the number of lines. Therefore, swap &a and &b in the first scanf, or swap the order of the nested for loops (but not both). Also, I had to add dummy scanf("...
2,193,399
2,197,145
How do I require const_iterator semantics in a template function signature?
I am creating a constructor that will take a pair of input iterators. I want the method signature to have compile-time const semantics similar to: DataObject::DataObject(const char *begin, const char *end) However, I can't find any examples of this. For example, my STL implementation's range constructor for vector is...
You could simply create a dummy function which calls your template with char * const pointers. If your template attempts to modify their targets, then your dummy function will not compile. You can then put said dummy inside #ifndef NDEBUG guards to exclude it from release builds.
2,193,605
2,196,852
Which boost libraries are heading for TR2?
If found this quote at boost.org: More Boost libraries are in the pipeline for TR2 It links to the TR2 call from proposals. But I can't seem to find any other information on which boost libraries are headed for TR2. I've seen a draft proposal for Boost.Asio, and I vaguely remember seeing something about Boost.System...
Sorry to answer my own question but after Neil's slap-in-the-face comment I had to find out for myself and none of the other comments were at all helpful. Wikipedia doesn't have a C++ Technical Report 2 page but it does have a tr2 section in the C++ Technical Report 1 page. Here is a quick list from Wikipedia. Boost.A...
2,193,944
2,194,114
Convert a Static Library to a Shared Library (create libsome.so from libsome.a): where's my symbols?
the title of this question is an exact dupe, but the answers in that question don't help me. I have a bunch of object files packed in a static library: % g++ -std=c++98 -fpic -g -O1 -c -o foo.o foo.cpp % g++ -std=c++98 -fpic -g -O1 -c -o bar.o bar.cpp % ar -rc libsome.a foo.o bar.o I'd like to generate libsome.so from...
Assuming you're using the GNU linker, you need to specify the --whole-archive option so that you'll get all the contents of the static archive. Since that's an linker option, you'll need -Wl to tell gcc to pass it through to the linker: g++ -std=c++98 -fpic -g -O1 -shared -o libsome.so -Wl,--whole-archive libsome.a I...
2,193,977
2,194,025
Why does GetLastError() return different codes during debug vs "normal" execution?
try { pConnect = sess->GetFtpConnection(ftpArgs.host, ftpArgs.userName, ftpArgs.password, port, FALSE ); } catch (CInternetException* pEx) { loginErrCode = GetLastError(); printf("loginErrCode: %d\n", loginErrCode); if(loginErrCode == 12013) { printf("Incorrect user name!\n"); ...
My memory is a little hazy in this regard, but what happens if you use the m_dwError field of the CInternetException object instead of calling GetLastError()? My guess is that something is causing the error code to be reset between when the actual error and your call to GetLastError(). I don't know why this happens wh...
2,194,050
2,195,250
Simple proxy program with BOOST
I'm trying to do a very simple program. It's actually a proxy, that I need to connect to it and that proxy fowards the packets to the outter world. I think of making a list of incomming packets, change the incomming port to a new port, forward the packet and wait for a response, and get the port number for the packet ...
You're in over your head, have you considered not coding it? Use socat: socat TCP-LISTEN:7656,bind=internal-ip,fork TCP:external-host:7656
2,194,100
2,194,328
FIFO list (moving elements) [C++]
Good evening, people! I'm trying to solve a rather simple problem, but.. well, it seems that I can't. :) The idea is that I have a FIFO list (FIFO queue) with n elements and it's given a value, k (k < n). My little program has to move the elements to the left with k elements. (e.g. for n=4, k=3, a[]=(1, 2, 3, 4), the r...
I'm not sure if I've understood your question completely. But looks like you effectively want to rotate the contents of the array. To rotate the array contents to the left k times. You can do the following: Reverse the first K elements. Reverse the remaining N-K elements. Reverse the entire array. Example: N = 5, K...
2,194,310
2,194,359
Getting 32 bit words out of 64-bit values in C/C++ and not worrying about endianness
It's my understanding that in C/C++ bitwise operators are supposed to be endian independent and behave the way you expect. I want to make sure that I'm truly getting the most significant and least significant words out of a 64-bit value and not worry about endianness of the machine. Here's an example: uint64_t temp; ...
6.5.7 Bitwise shift operators 4 The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value...
2,194,762
2,194,803
How to compare two objects (the calling object and the parameter) in a class?
I am writing a "Date" class for an assignment and I am having trouble doing one the of the functions. This is the header file for the class. class Date { public: Date(); // Constructor without parameters Date(int m, int d, int y); // Constructor with parameters. // accessors int GetMo...
int Date :: Compare (const Date& d) { if (year<d.year) { return -1; } else if (year>d.year) { return 1; } else if (month<d.month) { return -1; } else if (month>d.month) { return 1; } // same for day return 0; } Usually, you'lll also want to provide overloaded com...
2,194,827
2,195,044
How to modify the keyboard input in QT?
The following feature needs to be implemented to our existing QT & C++ application. We have to expand the user typed abbreviations into pre-defined words(s). The functionality we need to implement is something similar to text expander. Say if a user typed "FL", this needs to be replaced to "Florida" after immediately....
Could this example be useful to you ? They use a mecanism called completer, that provides different words for a given entry... It's quite like a dictionnary on a cell phone... Custom Completer Example : http://qt.nokia.com/doc/4.6/tools-customcompleter.html Hope it helps a bit !
2,194,904
2,195,006
What good are thread affinity mask changes for the current thread?
I'm writing a game engine and I need a way to get a precise and accurate "deltatime" value from which to derive the current FPS for debug and also to limit the framerate (this is important for our project). Doing a bit of research, I found out one of the best ways to do this is to use WinAPI's QueryPerformanceCounter f...
Unless a thread has a processor affinity mask, the scheduler will move it from processor to processor in order to give it execution time. Since moving a thread between processors costs performance, it will try not to move it, but giving it a processor to execute on has priority over not moving it. So, usually threads...
2,194,958
2,195,057
Should I cache the hash code of an STL string used as a hash key?
I've doing some performance analysis on the software I develop, and I've found that lookups on a global dictionary of URL's takes about 10% of the application's "load" phase time. The dictionary is implemented as a C++ STL std::map, which has O(lg n) lookups. I'm going to move it to a hash_map, which has roughly fixe...
I don't have experience with caching hash codes, but I've done some work recently converting std::map to std::tr1::unordered_map. Two thoughts come to mind. First, try profiling that relatively simple change first, because it sometimes makes things worse, depending on what your code is doing. It might give you enoug...
2,195,056
2,195,220
Error with using a function as a non-type template parameter
I have this template : template <class SourceFormat, class DestFormat, void (*convert)(DestFormat, SourceFormat)> static void _draw(...); And these functions : template <class Class1, class Class2> inline static void convertNone(Class1& dest, Class2& source) { dest = source; }; inli...
I don't know if you've done it intentionally, but your template parameters go Source/Destintaion and then Destination/Source. Notice that when you do _draw<unsigned __int32, unsigned __int8, &convertARGB_GREY>(...); your template definition fills them in as: SourceFormat = unsigned __int32 DestFormat = unsigned __int8 ...
2,195,276
2,195,305
A destructor - should I use delete or delete[]?
I am writing a template class that takes as an input a pointer and stores it. The pointer is meant to point to an object allocated by another class, and handed to the this containing class. Now I want to create a destructor for this container. How should I free the memory pointed to by this pointer? I have no way of k...
If you don't know whether it was allocated with new or new[], then it is not safe to delete it. Your code may appear to work. For example, on one platform I work on, the difference only matters when you have an array of objects that have destructors. So, you do this: // by luck, this works on my preferred platform //...
2,195,391
2,195,429
Linked List explanation required
I need to understand how a linked list works in this C++ code. I got it from my textbook. Could someone explain in detail what exactly is going on here? /*The Node Class*/ class Node{ private: int object; Node *nextNode; public: int get() { return obje...
what you've posted is a very basic implementation of a linked list. The objects that you're linking is "node". GetNext function gets the next node in the list and the setNex function gets the next node in the list. i'm sure the chapter should have an explanation for the code, at the very least the explanation for the c...
2,195,414
2,195,479
How to copy by value into a container class?
I am writing a sparse matrix class. I need to have a node class, which will be a template for its contents. My issue in writing this class is: How do I store the contents? I want to store the contents by value. If I stored it by pointer and it should be destroyed, then I'd have trouble. How can I safely perform a cop...
The standard C++ approach is to mandate that the type(s) used by your container class must be copyable (and perhaps assignable). It is a very reasonable requirement and is used by all of the container class templates in the standard library. For built-in types and simple POD-types, a user-declared copy constructor typi...
2,195,454
2,195,583
Visual Build professional compile errors?
I am using visual build professional and one of the steps is a 'Make VS 2003' (c++ project). However, every time I get the following error: fatal error C1033: cannot open program database '' If I compile the project myself in visual studios it works fine. Anyone know why this would be, or how I can fix it?
I think I have gotten that error in the past when I have an old .pdb file (or one that was somehow corrupted). If so, the error message should indicate which file it is. You should be able to manually delete that file. I think it has often been vc60.pdb. There is also some information about this error on msdn.
2,195,556
2,195,682
Detect Window Move in Property Page (win32)
I implemented a wizard using property sheet. One one page I display tooltip if user enters something invalid. It is a tracking tooltip so I have to manually turn it on and off. Now I want to move the tooltip when the wizard page moves. It seems that only the property sheet window receives WM_MOVE event from Windows. Th...
The property page isn't moving in relation to its parent window, the property sheet - that's why it's not getting WM_MOVE messages. You can set up a WM_MOVE handler in the property sheet and have it forward another message to the property page with PostMessage or SendMessage. I'd suggest a message in the WM_APP range.
2,195,760
2,195,779
Using pThreads, is it possible to write a function that can detect what thread it's being called from?
This is the usage case: Log(char* s); // prints out a log message Now: Log("hello world\n"); // called from Thread1 Desired output: Thread1: hello world Now: Log("hello world\n"); // called from Thread2 Desired output: Thread2: hello world I can have a map that maps thread pids to strings. What I need however, is ...
You'll need to pass pthread_self() into your Log() function (or write a macro).
2,195,815
2,196,516
How can I extend std::basic_streambuf to treat any iterable sequence as a stream?
Note: Edited based on responses to receive more appropriate answers. I have a collection of C++ templates that I've made over the years, which I call Joop. It comprises mainly libraries that don't quite fall into the "general-purpose" category but are just useful enough that I keep slapping them into different projects...
It can be confusing to look at the examples in sstream, but you probably don't want a new stream class at all. Looking now for an example at the basic_stringstream source, the only purpose of that class is to provide str function (it just calls the underlying buffer's str) avoid the underlying buffer's vtable when cal...
2,196,052
2,196,100
What is api interception? when is it used? how to implement it in C++
What is API interception When is it used How to implement it in C++
API interception is intercepting calls to a given DLL and re-directing them through your code. It is generally used to override some functionality provided by a DLL. An example is for adding a logo to a DirectX based game. How to implement it? Thats a complicated one and it depends on what sort of DLL you are try...
2,196,121
2,196,164
std::ostringstream woes
I can do std::ostringstream oss; oss << 1; oss.str(); so why can't I do: ((std::ostringstream()) << 1).str() ? Thanks!
The << operator returns the base type ostream, while the str member function exists only on the derived type ostringstream.
2,196,155
2,196,183
Is there anyway to write the following as a C++ macro?
my_macro << 1 << "hello world" << blah->getValue() << std::endl; should expand into: std::ostringstream oss; oss << 1 << "hello world" << blah->getValue() << std::endl; ThreadSafeLogging(oss.str());
#define my_macro my_stream() class my_stream: public std::ostringstream { public: my_stream() {} ~my_stream() { ThreadSafeLogging(this->str()); } }; int main() { my_macro << 1 << "hello world" << std::endl; } A temporary of type my_stream is created, which is a subclass of ostringstream. All o...
2,196,205
2,196,389
Composing objects of a class you inherit from?
I have a class Parameter, the purpose of which is to represent the possible values a certain parameter could hold (implements two key methods, GetNumValues() and GetValue(int index)). Often one logical parameter (parameter values are bit flags) is best represented by 2 or more instances of the Parameter class (i.e. a P...
I have a class which composes objects of a class it inherits from, which just doesn't seem right. Isn't that the definition of a composite? (parameter values are bit flags) This is the part of the design that I would question. Perhaps a better name for Parameter would be FlagSet? It's fine to hide the bitwise tests ...
2,196,300
2,196,359
Installing PySide - OSX
Anyone had success installing and using PySide on OSX? I am following the install instructions on the PySide site, though I'm running into issues building the API Extractor. I run cmake on the CMakeLists.txt file inside the api extractor dir and: This error is thrown- CMake Error at /Applications/CMake 2.8-0.app/Conte...
It's a set of quite widespread C++ libraries, they're probably needed by PySide, even though I've never tried it. Download them from there: http://sourceforge.net/projects/boost/files/boost/1.42.0/ Otherwise, you can install them from macports: http://www.macports.org once you've installed macports, just run "sudo port...
2,196,327
2,196,495
C++ destructor & function call order
Suppose I have the following snipplet: Foo foo; .... return bar(); Now, does the C++ standard guarantees me that bar() will be called before foo::~Foo() ? Or is this the compiler/implementation's choice? Thanks!
It is guaranteed behaviour. The actual execution is unrolled as follows: 0: enter block (scope) 1: Foo::Foo() 2. evaluation of bar(); as expression in return statement 3. save result of the expression as value returned from function 4. finalize return statement to leave function to its caller (request exit from current...
2,196,405
2,196,445
Virtual functions with two operands that can take many different types
Let me start with a concrete example. In C++, I have a hierarchy of classes under the abstract base class CollisionVolume. Any collision volume needs to be able to detectCollision with any other volume. This collision code is specialized based on the two subclasses in presence, but it is commutative: detectCollision(a,...
You're looking for multiple dispatch. C++ doesn't have it because it's hard to implement efficiently. Most other statically typed/efficiency-oriented languages don't either. Your RTTI solution is probably about the best way of faking it.
2,196,473
2,196,503
C++ Ramifications of ignoring exception from constructor
I've searched SO for an answer to this, but haven't found one. When an object throws an exception at the end of the constructor, is the object valid or is this one of those 'depends on the construction technique'? Example: struct Fraction { int m_numerator; int m_denominator; Fraction (dou...
Jonathan's answer is correct. In addition, while the fraction may be in a valid state, I would not recommend using exceptions for flow control, and especially for communication about the state of an object. Instead, consider adding some kind of is_exactly_representable to your Fraction object API that returns a bool.
2,196,725
2,200,375
QueueUserWorkItem with COM in C++
I have a performance issue where clients are creating hundreds of a particular kind of object "Foo" in my C++ application's DOM. Each Foo instance has its own asynchronous work queue with its own thread. Obviously, that doesn't scale. I need to share threads amongst work queues, and I don't want to re-invent the wh...
Have you verified what is taking so long? i.e. is it the call to CoInitializeEx()? You definitely don't need to call CoInitialize once per task. You also don't say how many threads you spawn, i.e. if your running on a dual core and your work is CPU intensive don't expect more than a 2x speedup, and if your work isn't...
2,196,841
2,197,203
can I use breakpoints with try catch statements with qt creator?
if an exception is thrown inside a try/catch, can i put a breakpoint there to get into debu mode before the program exits?
Tested here with a simple code, were I called a function that always throw. The breakpoints inside de catch block not ignored, and the debug mode started normally. Anyway, qtCreator uses GDB for debugging (At least on my machine). You can find out more about how GDB handle exceptions debugging here http://www.caf.dk/ca...
2,196,858
2,196,894
End of multi-dimensional array using compact pointer notation
For a 4-D array, I'm trying to average the values using compact pointer notation. Using examples from my text, it says I can use something like this: void DisplayAverage(double (*set)[DIM1][DIM2][DIM3]) double *ptr; double subTotal2 = 0; for (ptr = (double *)set; ptr < (double *)set + DIM0 * DIM1 * DIM2 * DIM...
You have one address-of too much: // notice: "set" instead of "&set" for (ptr = (double *)set; ptr < (double *)(set + DIM0); ptr++) { You were adding one to the address of your parameter (and thus were pointing to nowhereland), instead of DIM0 to the value of your parameter (which will bring you to after the array dat...
2,196,891
2,196,921
Returning an iterator to an element in STL Container
how would you check if the iterator that was returned by the function points to something in container class?
Iterators are passed around as [begin,end) pairs, with the end value signifying "not found" or other forms of the empty sequence. Return that from your function, or return a pair<bool,iterator> (or similar).
2,196,995
2,197,015
Is there any advantage of using map over unordered_map in case of trivial keys?
A recent talk about unordered_map in C++ made me realize that I should use unordered_map for most cases where I used map before, because of the efficiency of lookup ( amortized O(1) vs. O(log n) ). Most times I use a map, I use either int or std::string as the key type; hence, I've got no problems with the definition o...
Don't forget that map keeps its elements ordered. If you can't give that up, obviously you can't use unordered_map. Something else to keep in mind is that unordered_map generally uses more memory. map just has a few house-keeping pointers, and memory for each object. Contrarily, unordered_map has a big array (these can...
2,197,024
2,197,041
#include confusion and classes
I have been making several games with the Allegro API and C++. I have also been putting all my classes in 1 big main.cpp file. I tried many times to make .h and .cpp files, but my big problem is I have trouble with #including at the right place. For example, I want all my classes to access the allegro library without #...
I want all my classes to access the allegro library without #including allegro.h everywhere. Why? That is how you do it in C++ land. Could someone please explain how to correctly #include things. In .Net, everything seems to come together, but in c++ one thing cannot be used before it is included Conceptually, in ...
2,197,141
2,197,180
Function template specialization importance and necessity
I read C++ Primer, and it says function template specialization is an advanced topic, but I am totally lost. Can anybody offer an example why function template specialization is important and necessary? Why don't function templates support partial specialization while class templates do? What's the underlying logic?
Basically the idea is that you can write templates that behave in a generic way for the general case, but can still handle special cases. One example of where specialization is used is in std::vector. std::vector<bool> is a specialization that packs the bool elements such that they only use one bit per element, not o...
2,197,225
2,197,235
Using string functions (.substr) on arrays of strings
I have an array of strings, and need to grab substrings (the strings in between commas, in this case) and put them into another array of strings. I declare it as strings[numberOfTapes], so when I am searching for the commas I go character by character in a nested for loop, like so: for(int j = 0; j < tapes[i].length()...
tapes[i][j] is the character ',', and that character has no substr method. You probably wanted to call substr on the string object tapes[i], not on the single character. Also: You call substr(i-counter, counter) after you found a comma at position j. Is that your intention?
2,197,412
2,197,445
Reverse C-style String? - C++
I want to use pointers to reverse a char array in C++. I was wondering if there is anything that I should do differently? Am I doing this correctly? Is there a more efficient way to accomplish this? My small program: int main ( ) { char buffer[80]; PrintHeader(); cout << "\nString reversal program"; ...
void str_reverse( char *str ) { char *str_end = strchr( str, 0 ); std::reverse( str, str_end ); } if you're supposed to write a loop, void str_reverse( char *str ) { std::size_t len = std::strlen( str ); for ( std::size_t index = 0; index != len / 2; ++ index ) { std::swap( str[ index ], str[ l...
2,197,677
2,197,713
Mac vs. Ubuntu for C/C++ development?
I'm looking to buy a personal machine for development and I'm deciding whether to go with a Mac or a PC (on which I'd run Ubuntu). My plans for the next year or so involve getting more heavily into C/C++ and networking than I currently am. Are there any differences I should be aware of between the two OSes as far as ...
If you have a lot of excess cash laying around, get the mac with the option to run Ubuntu in a VM. Otherwise a pc gives just about as much flexibility. As far as the actual development environment, both are going to be similarly good, but Ubuntu might be just a bit more developer friendly: apt certainly does make it ...
2,197,834
2,197,861
Is the following valid C++ code?
If it is, what is it supposed to do? typedef struct Foo_struct{ Dog d; Cat* c; struct Foo_struct(Dog dog, Cat* cat){ this->d = dog; this->c = cat;} } Foo; (back story: porting a program written in Visual C++ (on Windows) to g++ (on MacOSX); no idea what this code is suppoesd to do). Thanks!
I don't think it is. (And Comeau agrees with me.) You cannot define a constructor like this. In C++, struct names are first-class citizens. There's no need to employ the old typedef trick from C. Also, d and c should be initialized in a member initialization list. This would be valid (and better (C++): struct Foo { ...
2,198,146
2,198,177
memory questions, new and free etc. (C++)
I have a few questions regarding memory handling in C++. What's the different with Mystruct *s = new Mystruct and Mystruct s? What happens in the memory? Looking at this code: struct MyStruct{ int i; float f; }; MyStruct *create(){ MyStruct tmp; tmp.i = 1337; tmp.j = .5f; return &tmp; } int m...
When you use the new keyword to get a pointer, your struct is allocated on the heap which ensures it will persist for the lifetime of your application (or until it's deleted). When you don't, the struct is allocated on the stack and will be destroyed when the scope it was allocated in terminates. My understanding of yo...
2,198,163
2,198,437
What are the pros and cons of using Matrices, Euler Angles, and or Quaternions for rotation representation?
Matrices and Euler angles can suffer from Gimbal lock but what are some other arguments for using one over the other? What do you think DirectX favors? What do you use in daily C++/C/DirectX programming?
Euler angles only require three parameters, as opposed to storing a matrix (or three, but that sounds excessive). When you apply the Euler rotation, however, you will possibly end up with something equivalent to three matrix multiplications to create the transformation. If you were only using a matrix, you might not in...
2,198,186
2,198,221
Purpose of #ifndef FILENAME....#endif in header file
I know it to prevent multiple inclusion of header file. But suppose I ensure that I will include this file in only one .cpp file only once. Are there still scenarios in which I would require this safe-guard?
You can guarantee that your code only includes it once, but can you guarantee that anyone's code will include it once? Furthermore, imagine this: // a.h typedef struct { int x; int y; } type1; // b.h #include "a.h" typedef struct { type1 old; int z; } type2; // main.c #include "a.h" #include "b.h" Oh, no! Our main.c...
2,198,239
2,205,787
What's the best alternative library to gettimeofday() in C++?
Is there a more Object Oriented alternative to using gettimeofday() in C++ on linux? I like for instance to be able to write code similar to this: DateTime now = new DateTime; DateTime duration = new DateTime(2300, DateTime.MILLISECONDS) DateTime deadline = now + duration; while(now < deadline){ DoSomething(); ...
So porting boost wasn't an option for my target. Instead I had to go with gettimeofday(). There are however some nice macros for dealing with timeval structs in sys/time.h #include <sys/time.h> void timeradd(struct timeval *a, struct timeval *b, struct timeval *res); void timersub(struct timeval *a, struc...
2,198,255
2,205,137
Which kind of cast is from Type* to void*?
In C++ for any data type I can do the following: Type* typedPointer = obtain(); void* voidPointer = typedPointer; which cast is performed when I assign Type* to void*? Is this the same as Type* typedPointer = obtain(); void* voidPointer = reinterpret_cast<void*>( typedPointer ); or is it some other cast?
It is a standard pointer conversion. Since it is a standard conversion, it doesn't require any explicit cast. If you want to reproduce the behavior of that conversion with an explicit cast, it would be static_cast, not reinterpret_cast. Be definition of static_cast given in 5.2.9/2, static_cast can perform all conversi...
2,198,316
2,198,334
Why can't I multi-declare a class
I can do this extern int i; extern int i; But I can't do the same with a class class A { .. } class A { .. } While in both cases no memory is being allocated.
The following are declarations: extern int i; class A; And the next two are definitions: int i; class A { ... }; The rules are: a definition is also a declaration. you have to have 'seen' a declaration of an item before you can use it. re-declaration is OK (must be identical). re-definition is an error (the One Def...
2,198,379
2,198,400
Are virtual destructors inherited?
If I have a base class with a virtual destructor. Has a derived class to declare a virtual destructor too? class base { public: virtual ~base () {} }; class derived : base { public: virtual ~derived () {} // 1) ~derived () {} // 2) }; Concrete questions: Is 1) and 2) the same? Is 2) automatically virtua...
Yes, they are the same. The derived class not declaring something virtual does not stop it from being virtual. There is, in fact, no way to stop any method (destructor included) from being virtual in a derived class if it was virtual in a base class. In >=C++11 you can use final to prevent it from being overridden i...
2,198,471
2,198,578
How to suppress individual warnings in C++?
First of all, sorry if this is an obvious question, but I'm rather new to C++. Also, this code is not originally mine, but I am trying to clean it up. I'm looking for a compiler independent way to surpress warnings (preferably) for a specific line. I've got the following code: int MPtag::state_next( int i, int s ){ #i...
The easiest way is of course to make the parameter disappear when not needed, like so: int MPtag::state_next( int #if NGRAMS != 2 i #endif , int s ) { #if NGRAMS==2 return s+1; #elif NGRAMS==3 return tag_at(i,0) * num_tags + s+1; #elif NGRAMS>=4 return tag_at(i,-1) * num_tags*num_tags + tag_at(i,0)*num_ta...
2,198,612
2,198,706
Why is my adjacency list showing duplicate edges?
#include <iostream> using namespace std; struct node { int v; node* next; node (int x, node* t) { v = x; next = t; } }; typedef node *link; int **malloc2d(int, int); void printMatrix(int **, int); link *convertToList (int **, link *, int); void printList (link * a, int size); //...
Your print function is also wrong, and it destroys the list while printing without freeing any of the memory. It should read something like this: void printList (link * a, int size) { for (int i = 0; i < size; i++) { for (link finger = a[i]; finger != NULL; finger = finger->next) { ...
2,198,636
2,198,748
Input output communication between two programs
I have a third party java program called kgsgtp.jar which need to communicate with my own C++ (but mainly just C) program. The documentation for the java program states: ===================== You just need to make sure that stdin for kgsGtp it connected to the engine's output and stdout for kgsGtp is connected to t...
That description is for unixes, where a sequence of pipe(),dup2(), fork()/exec() calls would be use to do this. Take a look at the code snippet in the answer from denis here: How do I get console output in C++ with a Windows program? , should get you started. Edit: more complete example is here: http://support.microsof...
2,198,908
2,198,941
ofstream - detect if file has been deleted between open and close
I'm wriiting a logger on linux. the logger open a file on init. and write to that file descriptor as the program run. if the log file will be deleted after the file descriptor was created, no exception/error will be detected . i have tried: out.fail() !out.is_open() i have google this and find this post . http://www....
Files are 'unlinked' by rm. A file can have many names. When it has no names left, and nobody has it open, then it is reclaimed by the file system and the space it occupies can be reused. Linux has an API for 'watching' files called inotify, but this is inviting complexity and race conditions. So the bigger question i...
2,198,950
2,198,975
Why is (void) 0 a no operation in C and C++?
I have seen debug printfs in glibc which internally is defined as (void) 0, if NDEBUG is defined. Likewise the __noop for Visual C++ compiler is there too. The former works on both GCC and VC++ compilers, while the latter only on VC++. Now we all know that both the above statements will be treated as no operation and n...
(void)0 (+;) is a valid, but 'does-nothing' C++ expression, that's everything. It doesn't translate to the no-op instruction of the target architecture, it's just an empty statement as placeholder whenever the language expects a complete statement (for example as target for a jump label, or in the body of an if clause)...
2,199,043
2,199,956
C++ Operator overloading example
Well, I'm new to operator overloading, and I found this problem. Instead of documenting myself, I prefer to ask you :D The point is, I know how to do simple operator overloading, but I'm facing problems with stacking operators. I'll try to put a relatively simple example: struct dxfdat { int a; string b; /* here is...
It's quite easy, don't panic :) You have recognized the problem well: it's very similar to the std::cout - std::endl work. You could do like such, though I'll rename the types, if you don't mind. struct EndMarker {}; extern const EndMarker end; // To be defined in a .cpp class Data { public: Data(): m_data(1, "") {}...
2,199,061
2,199,231
LD_DEBUG=files for Windows Visual Studio?
I'm quite stuck on a ddl loader problem under Windows Visual Studio 2009 C++. I have a framwork which loads plugins as DLL files, unfortunatly I have no sourcecode access to the framework. The dependency walker doesn't show any errors, but the framework just says "dependencies not found" when loading the plugin. I'm q...
If you use dependency walker it has a menu entry Profile. So if you load the exe to the dependency walker and use profile you might get additional information why dll wasn't resolved.
2,199,076
2,199,139
Printf and scanf work without stdio.h, why?
Possible Duplicate: Why #include <stdio.h> is not required to use printf()? Both printf and scanf have been declared in stdio.h. But they work even without that, dropping just a warning message? What's the theory behind this?
Calling a function without declaring it will create an implicit declaration based on the parameters you give and an assumed return type of int. This lets it get past the compilation stage, since the function could exist somewhere else that isn’t known until link time — C didn’t always have function prototypes, so this ...
2,199,251
2,199,390
What's the point of "typedef sometype sometype"?
Lately I've run into the following construction in the code: typedef sometype sometype; Pay attention please that "sometype" stands for absolutely the same type without any additions like "struct" etc. I wonder what it can be useful for? UPD: This works only for user defined types. UPD2: The actual code was in a temp...
How about to make Template parameters visible to outside entities? template <class Foo> struct Bar { typedef Foo Foo; }; int main() { Bar<int>::Foo foo = 4; } Note: this is actually not allowed in standard C++, but is specific to MSVC. See comments.
2,199,614
2,199,662
C++ How to store collection of templates objects regardless of tempate
I have a problem with implementing database table library. I have a class Column storing different types. template <class T> class Column : iColumn<T> { ... } Table is composed of columns, so I need a collection of them (map with string name as a key and column as value). How shall I implement one collection of all ...
You should have a common interface. class Column<T>: public IColumn { ... }; std::map<std::string,IColumn*> columns;
2,199,868
2,267,748
c++ runtime error? how to solve this and check?
#include<iostream> using namespace std; int main() { int hash, opp, i, j, c = 0; //cout<<"enter hasmat army number and opponent number\n"; while(cin>>hash>>opp) { cout<<opp-hash<<endl; } } time limit for this problem: 3.000 seconds how can i verify and test this condition? i'm submittin...
Once you've compiled your program, check its running time by running it with the Unix program time: time ./myprogram This will print how much "real" (human) time was taken, and how much CPU (active processing) time. If you want to check how much memory your program uses, run it in the debugger and set a breakpoint whe...
2,199,896
2,200,087
Running app as Windows Service reports COM error 80040154
I'm trying to convert a normal application to a service. The application uses an installed COM component. When its run as a standalone application, this finds and connects to the COM component, however having converted the app to a service, I get the above error. I understand that this could be related to the fact tha...
Clearly your COM server hasn't been properly registered. Once difference for a service is that it usually runs under a different account. Use Regedit.exe and make sure the registration is present in HKLM\Software\Classes\CLSID and not in HKCU. Reregister, this time make sure that you are running Regsvr32.exe in a ad...
2,199,951
2,216,097
ComServer that should return a ComObject
What I am trying to do is transfer an object that has been created on the serverside to the client. I have got it to work well when I using c++ on both server and client side, but I do not get my server to work correct with other languages like .Net, It probably doesn't like the pointers! Does this Serversidecode look ...
Asside from TServerDidleComTestImpl::GetMyObject() not compiling due to you trying to assign a DummyComObj ** to a DummyComObj*, but you are also completely ignoring COM reference counting rules. Try this instead: Server Form: .h #include <utilcls.h> class TForm2 : public TForm { __published: // IDE-managed Componen...
2,199,969
2,199,999
Pass the current state of a function into another function in C/C++
Is there a way to pass the current state of a function into another function in C/C++? I mean all the parameters and local variables by current state. For example: void funcA (int a, int b) { char c; int d, e; // Do something with the variables. // ... funcB(); // Do something more. } void func...
Introduce a common struct. struct State { char c; int d,e; }; void funcA(int a, int b){ State s; s.d = 1234; // ... // ... funcB(s); } void funcB(State& s) { //... }