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 |
|---|---|---|---|---|
4,301,505 | 4,302,255 | Compile errors when I using CRT Memory Leak Detection | To detect memory leak, new keyword is re-defined.
It's OK if I use [Type 1]. But compile error is occured if I uncomment [Type 2].
Is there any way to use both type of new?
#include <crtdbg.h>
#define new new(_CLIENT_BLOCK, __FILE__, __LINE__)
struct Foo
{
int m_N;
Foo() : m_N( 0 ) {}
};
int main( int argc, char* ... | Because your macro causes your placement new to expand to:
Foo* pFoo2 = new(_CLIENT_BLOCK, __FILE__, __LINE__) (pFoo) Foo();
which is clearly invalid syntax.
A MSFT engineer confirms:
#define of new is not compatible with placement new
so you can't use it with crtdbg.h.
|
4,302,006 | 4,302,120 | How to bind a constructor in C++? | Needless to over explain. The following code is self-evident:
struct X
{
X(int n){}
};
int main()
{
std::vector<int> src;
std::vector<X> dest;
// Below is not valid in current C++, but that is just what I want.
transform(src.begin(), src.end(), back_insert(dest), std::bind(&X::X, _1));
}
A con... | Since X is implicitly constructible from int, a simple copy should achieve the conversion.
copy(src.begin(), src.end(), std::back_inserter(dest));
Or even using the vector's constructor:
std::vector<X> dest(src.begin(), src.end());
In the general case, boost's lambda library has a constructor functor.
#include <bo... |
4,302,008 | 4,302,099 | Strange problems with new/delete in an app that uses my DLL | sorry for the cryptic question title. I'm having a strange problem and i have no idea why it is happening. Fortunately, the code involved is pretty simple. But beofre we get to it, let me briefly describe my app. It is a multithreaded app that serves a large amount of data. Something like an in-ram database. It is poss... | Well the clue appears to be in the callstacks. In the "delete" callstack you'll notice it is calling various delete functions etc directly in mydll.dll. In the allocation the allocation is being performed by msvcr90d.dll.
What you have is a /MDd (or /MD in release) flag set on your exe and a /MTd (or /MT in release) ... |
4,302,011 | 4,302,023 | Boost tuple performance | According to boost::tuple documentation, accessing a single element of a tuple has the same performance as accessing a member variable. For example, given the following declaration:
tuple<A, B, C> t1(A(), B(), C());
struct T { A a; B b; C c; }
T t2;
These two statements should have equal (or with negligible difference... | You are correct about the list-like performance. However, it can be resolved at compile-time and hence boils down to O(1) at run-time. (Given a sufficiently good optimizing compiler.)
|
4,302,098 | 4,302,126 | Trying to create CAS template | at the moment I'm busy fiddling with CAS operations and lock/wait-free algorithms, and for my own sanity I decided to implement a template to handling all the casting for me:
VC6:
template <typename T> static inline T CAS(volatile T* pDest, T pCompare, T pValue)
{
//static_assert(sizeof(T) != sizeof(PVOID),"CAS req... | OK if i call the CAS function as follows:
CAS<int*>( &p, NULL, pi );
Then I get a different error:
error C2664: 'CAS' : cannot convert parameter 1 from 'volatile int **' to 'int *volatile *'
This gives more of a clue as to what is going wrong.
One way to solve it would be to introduce a typedef as follows:
typede... |
4,302,107 | 4,302,509 | Looking for papers/research on linking/compile time optimizations for report | I was wondering whether anyone had any good resources (papers/articles/book references) on compile/linking optimizations.
I had worked in two companies that performed their linking operations differently.
The First Company forced a strict DAG structure for the code explaining to me that with a forced tree structure th... | That's not exactly recent, but this site has a series of interesting articles regarding physical structure and compilation time. You may also want to know that what you encountered in the second company is often referred to as the Single Compilation Unit technique.
|
4,302,364 | 4,302,458 | convert BSTR to const char* |
Possible Duplicates:
Which is better code for converting BSTR parameters to ANSI in C/C++?
How to convert char * to BSTR?
How I can convert BSTR to const char*?
| A BSTR is actually a WCHAR* with a length prefix. The BSTR value points to the beginning of the string, not to the length prefix (which is stored in the bytes just “before” the location pointed to by the BSTR).
In other words, you can treat a BSTR as though it is a const WCHAR*. No conversion necessary.
So your questio... |
4,302,455 | 4,306,842 | Showing Image Acquisition's Device Interface | I'm using TWAIN 2.1, to connect to Scanner, let user change any option, and wait for input, the problem whenever the scanner interface shows, the cursor still give indication about certain loop, or working,,, this is the following code:
HWND g_hwnd = CreateWindow ("STATIC",
"",
... | Have you considered EZTwain? It's free and very easy to use
http://www.dosadi.com/eztwain1.htm
In your case, I think the problem is with not implementing the // TO-DO. TWAIN uses the message loop to communicate, and so does Windows (to draw dialogs, for example).
I assume that your loop is actually doing something mo... |
4,302,467 | 4,302,477 | C++ Delete array of c-strings/other type of array | [EDIT]
Okay, so that makes sense, thank you sharptooth and CashCow. You can't delete data allocated as const, which makes string literals out of the question. So if I change my initialization to look like this:
char **groups = new char*[2];
char *s1 = new char[10];
char *s2 = new char[10];
char c1 = 'a';
char c2 = 'b'... | You try to deallocate string literals - that's undefined behavior:
char *groups[] = {"testing1", "testing2"};
delete[] groups[i];
only call delete[] on pointers returned by new[].
|
4,302,864 | 4,303,386 | How to parse TCP packet payload | I'm using pcap to capture TCP packets for which I would like to parse the payload. My strategy is as follows:
Get the ethernet header and check if it has type ETHERTYPE_IP (IP packet)
Check if the IP packet has protocol IPPROTO_TCP (TCP packet)
Check for payload size > 0 (size = ntohs(ip_header->total_length - ip->hea... | Only by analyzing content. Nothing in IP or TCP header what can mark "HTTP Request" packets. Even "first data packet in connection" wouldnot work because there are persistent connections.
Also, to be completely sure about catching all URIs you need to reassemble TCP stream and parse HTTP request: URI can be split on tw... |
4,303,070 | 4,303,773 | Porting REST API connection code to Android NDK in c++ | I have an Android application in the market which connects and send POST and GET queries to a REST API, and then stores the results in a DB which are then queries and displayed in an appropriate manner in the application.
I'm interested in speeding up the application and have noticed quite a lot of lag between the time... | I'm doing the EXACT same thing, and trust me: if you have no previous C++ experience, this might be a bit too costly for little benefit.
In my case, after some profiling, I reordered things around and had an initial jump in performance only by dropping DOM and using SAX. All the rest is only making things marginally b... |
4,303,218 | 4,303,325 | c++ setting timeval members | I have a function which takes two current class level member variables and sets them into a timeval structure, and returns the timeval obj (by value).
I am seeing an issue when setting a class level member timeval object vs creating a new timeval object at each get() call.
Inside the class
protected:
int time[2];
timev... |
Any chance you've corrupted something somewhere else (undefined behaviour)?
Are you using threads? If so, the first approach could have two threads both working on the class member 'tv' at the same time, whereas the second approach has each thread working on its own local timeval instance.
That said, there's really n... |
4,303,513 | 4,306,581 | push_back vs emplace_back | I'm a bit confused regarding the difference between push_back and emplace_back.
void emplace_back(Type&& _Val);
void push_back(const Type& _Val);
void push_back(Type&& _Val);
As there is a push_back overload taking a rvalue reference I don't quite see what the purpose of emplace_back becomes?
| In addition to what visitor said :
The function void emplace_back(Type&& _Val) provided by MSCV10 is non conforming and redundant, because as you noted it is strictly equivalent to push_back(Type&& _Val).
But the real C++0x form of emplace_back is really useful: void emplace_back(Args&&...);
Instead of taking a value_t... |
4,303,599 | 4,440,794 | Edit and Continue on GDB | I know that E&C is a controversial subject and some say that it encourages a wrong approach to debugging, but still - I think we can agree that there are numerous cases when it is clearly useful - experimenting with different values of some constants, redesigning GUI parameters on-the-fly to find a good look... You nam... | It is a surprisingly non-trivial amount of work, encompassing many design decisions and feature tradeoffs. Consider: you are debugging. The debugee is suspended. Its image in memory contains the object code of the source, and the binary layout of objects, the heap, the stacks. The debugger is inspecting its memory ... |
4,303,607 | 4,328,024 | Deterministically Generating cryptographically secure keys and IVEC's | Background
I am designing a system which enables the development of dynamic authentication schemes for a user of static web content. The motivation is to pre-generate large amounts of complex-to-generate, yet sensitive web-content, and then serve it statically with cookie-based (embedding reversably encrypted informat... | Interesting question.
First, your Initial Vectors don't have to be cryptographically strong random quantities, but they should be unique per-message. The IV is really just a kind of salt value that ensures that similar messages encrypted using the same key don't look similar once they're encrypted. You can use any quic... |
4,303,781 | 4,304,758 | Help me with this boost::lambda::if_then expression calling a functor | Please have a look at the following simplified example:
#include <vector>
#include <string>
#include <algorithm>
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/if.hpp>
using namespace boost::lambda;
namespace bl = boost::lambda;
using namespace std;
struct Item
{
strin... | ronag is correct, boost's lambda reference mentions that "They all take lambda functors as parameters and return void."
It seems that the alternative syntax (bl::if_(condition)[function]) does not require lambda functors.
However, another big problem is that for_each returns the functor which is a boost lambda object, ... |
4,303,818 | 4,304,123 | Qt programming: How to use custom data type in QVariantMap? | I am writing a Qt app that maps a C++ class to Javascript object in QtWebkit. Firstly let me explain what I am trying to do:
I have a class inherited from QObject:
class myobj : public QObject {
Q_OBJECT
public:
myobj();
~myobj();
pulbic slots:
void getData();
}
And in another class I tried to add myo... | Like the compiler said, no constructor of QVariant exists that take a myobj as parameter. Have you tried to use the qVariantFromValue function instead?
I think this is what you are searching for.
|
4,303,851 | 4,304,018 | 3d game with Python, starting from nothing | So we want to program a 3d game for school, we can probably use blender for the 3d models, however we are totally clueless as to how to use them in a game/application.
Are there any recommended guides/documents we should read on general 3d game programming and perhaps python specific stuff.
We are also possibly conside... | There's Pygame: A game framework for the Python language. If you need to know the basics for game development (engine, flow, ui, mathematics), this framework with all its examples will help you a lot. This won't take you by the hand and guide you step by step through game-development, but if you need a reference and a ... |
4,303,860 | 4,304,436 | GNU Inline assembly problem | I did some refactoring at c167 platform specific code and I stumbled upon an inline assembly problem.
Previous code:
asm volatile ( "
extp #pag:%0, #3
mov r4, pof:%0 @ R4 = g_nRcvBufCount
sub r4, #1 @ R4 = R4 - 1
mov pof:%0, r4 @ g_nRcvBufCount = R4... | Look at the asm in the warning message:
extp #pag:[r2+#66],#3
Apparently the #pag: thing is valid with a register or absolute address after it, but not with a more complex expression already containing an offset like [r2+#66]. You might need to switch to using a "r" argument containing the address of cfg->g_nRcvBufCou... |
4,303,941 | 4,304,205 | How to declare an object from a condition and make it available through the rest of the function? | I have two classes, both with the same function names that do similar things based on user input. I need to do something like this.
if (myapp.advanced == true)
class1 a;
else
class2 a;
But since a is declared from inside the if, it's not available in the next line. How do fix the above condition?
a.something(... | If these types are related, use a common base class and do this:
const base& a = (myapp.advanced == true) ? static_cast<base&>(class1())
: class2();
a.something();
a.some_other_thing();
a.yet_another_thing();
Temporaries bound to a const reference have their lifetimes extended... |
4,303,995 | 4,306,578 | Libserial Open() freezes in my C++ program | Basically I have a really simple C++ program where I'm trying to open a serial port (which is actually a USB->RS232 converter, should be supported by libserial) but the code freezes on Open(). No errors no exceptions, nothing, it just does nothing. It seems to work on other serial ports except this specific one. The se... | I looked at libserial a couple of years ago when I was having to write a control interface to a modem that allowed remote control via RS-232. I ended up going with the Boost's ASIO implementation for utilizing the serialport.
Not sure if Boost.ASIO will work for you or not. but in my experience I haven't had it hang o... |
4,304,068 | 4,304,316 | Saving custom application notifications, error strings | what is the best way to save notify, error, warning string for GUI application? Currently I just create const char* strings everytime the application needs to process and popup a notification string. how should i handle messages without regenerating memory for temporary strings?
| Since You tagged win32api I think You are using windows :D...
So one solution would be to save your strings as resources.
They are easy to maintain and can be changed/updated easily...
Hope this helps:)...
|
4,304,223 | 4,304,250 | Default parameter for a list reference | In C++, how would I specify a default value for a list reference in a function?
void fun(
std::list<My_Object *> &the_list,
int n = 4
)
| if it is a plain reference, the only thing you an default it to is a valid lvalue which probably is not available. But if it is a reference to const you could default it to an empty list like this:
void fun(
std::list<My_Object *> const & the_list = std::list<My_Object *>(),
int n = 4
)
If you have a list named ... |
4,304,600 | 4,304,902 | Matrix multiplication: Strassen vs. Standard | I tried to implement the Strassen algorithm for matrix multiplication with C++, but the result isn't that, what I expected. As you can see strassen always takes more time then standard implementation and only with a dimension from a power of 2 is as fast as standard implementation. What went wrong?
matrix mult_strasse... | Some thoughts:
Have you optimized it to consider that a non-power of two sized matrix is filled in with zeroes? I think the algorithm assumes you don't bother multiplying these terms. This is why you get the flat areas where the running time is constant between 2^n and 2^(n+1)-1. By not multiplying terms you know are ... |
4,304,661 | 4,304,698 | possible problems after resizing dynamic array | Got little problem here.
I created dynamic array:
m_elements = new struct element*[m_number_of_elements];
for(int i = 0; i < m_number_of_elements; i++)
{
m_elements[i] = new struct element[m_element_size];
}
then I tried to resize existing array:
m_elements[m_number_of_elements] = create_more_el... | You should use std::vector for it, then you can with new allocate memory for new struct and push her pointer to vector, if you deleting you should delete on pointer.
|
4,304,662 | 4,304,690 | Concatenating strings doesn't work as expected | I know it is a common issue, but looking for references and other material I don't find a clear answer to this question.
Consider the following code:
#include <string>
// ...
// in a method
std::string a = "Hello ";
std::string b = "World";
std::string c = a + b;
The compiler tells me it cannot find an overloaded ope... | Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:
std::string c = "hello" + "world";
This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can... |
4,305,002 | 4,305,043 | Erasing a pointer from a vector | I'm trying to erase a pointer to an object, but I keep crashing the console (PS2), I don't get any errors due to the way the console is set up, so I'm not quite sure what is going on.
I've listed the two lines that error, this didn't error until I added these lines.
for(listIter = m_downDirectionList.begin(); list... | for(listIter = m_downDirectionList.begin(); listIter != m_downDirectionList.end(); )
{
Projectile* proj = dynamic_cast<Projectile*>(*listIter);
if (proj->getZWorldCoord() >= (defaultLevelDepth + zOffset))
{
proj->getPoolOwner()->releaseAProjectile(proj);
listIter = m... |
4,305,179 | 4,306,982 | JSF frontend calling C++ event handler client functions | I have a huge code written in C++. The code has around 300 screens.
I want the new screens to be written in JSF.
However, rewriting the the existing C++ code is a lot of work.
Is there a way to create a generic code to interact between HTML/JSF components and C++ components?
My problem is that I feel that C++ componen... | Yes, there is no 'automatic' way or tool to create JSF screens from Delphi / C++Builder forms.
If the code base follows a clean model/view/controller architecture, maybe with some effort the C++ side can be extended by a service layer, which could be accessed from the Java side using JNA, web services, a message-orient... |
4,305,355 | 4,305,442 | How get fileName having FILE*? | In my class I have FILE* ascii_file; data member, which always is initialized via class constructor. How can I get full path of the asci_file? I don't want to store more information about the file expect ascii_file, and want it to work on windows, linux and solaris.
| This task is going to require non-portable code.
On Windows you can convert FILE* to CRT file descriptor using _fileno, and then convert to an OS handle using _get_osfhandle.
Then you can get the filename as shown here (using file mapping).
Obtaining a File Name From a File
Handle
|
4,305,562 | 4,305,730 | How to cross-reference already existing doxygen docs? | I have two C++ projects A and B; The dependency is only B to A.
B --> A
I would like to separately run Doxygen on A and B respectively but still let me possible cross reference on A from B doc. (That is, when I browse B doc, I can directly link to the A doc if there is any Class from A used in B).
--
[Replied the ans... | You probably want to use the tagfile feature. When you generate the documentation for A, make sure the GENERATE_TAGFILE option is set. When you generate the documentation for B, set the value of TAGFILES to include the result from A.
[Update to address relative paths]
Doxygen is fairly fragile when it comes to [relativ... |
4,305,597 | 4,305,758 | Access to base class function | class Base
{
public: void foo(){}
};
class Derived : public Base
{
private:
using Base::foo;
};
int main()
{
Derived d;
d.foo();
}
Is the code legal? The declaration using Base::foo is in the private section of the derived class. So the call d.foo() shouldn't compile, am I right?
| The Standard in section 11.2/4 says
A member m is accessible when named in class N if
— m as a member of N is public, or
— m as a member of N is private, and the reference occurs in a member or friend of class N, or
— m as a member of N is protected, and the reference occurs in a member or friend of class N, or ... |
4,305,721 | 4,305,752 | What will happen if you delete this in C++ |
Possible Duplicate:
Is it OK to use “delete this” to delete the current object?
I just saw some code where they have done delete this; in a class function, I know that this is not a good design but is it defined what will happen, lets say that the class always is a pointer from somewhere. Will it always be deleted i... | It is perfectly legal in C++ to delete this and is actually very useful for certain patterns like smart pointers. The burden is on the developer though to make sure that no other methods are called or on the stack for this which will access instance data after the delete occurs.
The C++ FAQ Lite has an entry for this... |
4,305,819 | 4,305,852 | C++ Bars in function parameters | int fd = open(JOYSTICK_NAME, O_RDONLY | O_NONBLOCK);
What does the bar between O_RDONLY and O_NONBLOCK mean? I've encountered this in OpenGL/GLUT programming and I was curious on the semantics.
| This is the bitwise OR operator. It takes the individual bits in O_RDONLY and combines them with the bits in O_NONBLOCK, and returns the combined value.
For example, suppose the binary value for O_RDONLY is 11001100 and the binary value for O_NONBLOCK is 00001111. OR-ing these together yields 11001111.
|
4,306,122 | 4,306,356 | How to determine primary network adapter in results from PdhExpandWildCardPath? | My goal is to measure the average Bytes received per second using the Windows performance counter API. My problem is that, when there are multiple network adapters, I don't know which one is the "primary" one (i.e. the one used for Internet and LAN traffic).
I can pass "\Network Interface(*)\Bytes Received/sec" to Pdh... | Which network adapter is 'Primary' is a qualitative judgment. A computer might have both onboard wireless 802.11, and wired Ethernet adapters, either of which could be primary at any given time (or even at the same time).
You are probably going to have to use the IP Helper API to determine which you prefer and corre... |
4,306,198 | 4,306,453 | using virtual functions versus static_cast from base to derived | I am trying to understand which implementation below is "faster". Assume that one compiles this code with and without the -DVIRTUAL flag.
I assume that compiling without -DVIRTUAL will be faster because:
a] There is no vtable used
b] The compiler might be able to optimize the assembly instructions because it "knows" ex... | It depends on the platform and the compiler. A switch statement can be implemented as a test and branch or a jump table (i.e., an indirect branch). A virtual function is usually implemented as an indirect branch. If your compiler turns the switch statement into a jump table, the two approaches differ by one additional ... |
4,306,236 | 4,306,306 | Can anybody explain me this code? | aCCB->C16_ArgInfo(aCCB->InstHdl,2,&tType2,&tOpt2,&tLen2,NULL,&tCount2);
if (tType2 == _TypeAlpha &&
tOpt2 == (_ArgOptVAR | _ArgOptARRAY))
{
/* read array */
tBuf = static_cast<char*>(malloc(tLen2));
aCCB->C16_ArgRead(aCCB->InstHdl,2,0,tBuf);
tTab = static_cast<char**>(malloc(sizeof(char*) * tCou... | It loops through the array, assigning the value of the previous iteration plus tSize. What that means or why...how the hell should I know?
I wouldn't be too hard on yourself for not being able to make sense of that code. It's very hard to read.
Edit:
Oh man. Just read one of the comments to the OP and looked at it s... |
4,306,261 | 4,306,366 | Map function in C++ with templates | I'm trying to learn templates in C++ and one of the things I was trying was to code a map function like the ones you typically find in functional languages. The idea was something like this:
template <class X> X * myMap(X * func(X), X * array, int size)
{
X * temp;
for(int i = 0, i < size, i++) {temp[i]... | You're just getting the syntax for a function pointer wrong here. You want to say:
template <class X>
X* myMap(X (* func)(X), X * array, int size)
{
...
}
To make this function more generic, use a template parameter instead of a function pointer so you can use both plain function pointers and C++ function object... |
4,306,630 | 4,306,658 | CreateWindow Fails as Unable to Find Window Class - C++ | In my application the function CreateWindow is failing for some reason. GetLastError indicates error 1407, which, according to the MSDN documentation is "Cannot find window class." The following code shows how CreateWindow is being called and the respective variables names at time of call:
m_hInstance = ::GetModuleHa... | You have to call RegisterClassEx before you can use the window class on CreateWindow.
Example code here.
Each process must register its own
window classes. To register an
application local class, use the
RegisterClassEx function. You must
define the window procedure, fill the
members of the WNDCLASSEX struct... |
4,306,649 | 6,345,671 | C# Interp. for Active Shape Models library in C++ | Stasm (http://www.milbo.users.sonic.net/stasm/index.html) is a C++ library for finding features on image, applying the concept of active shape models.
I am trying to use AsmSearchDll which is on stasm DLL (stasm_dll) like this on a C# project. In C++ the prototype is
void AsmSearchDll(
int *pnlandmarks, // out: numbe... | I tried to bind the same function to python unsuccessfully.
You have first to allocate the landmarks array and an int, before passing pointer to the function.
The function need a lot of configuration file in ../data/, be sure it is there.
The imagename string should actually be the FILEPATH of the image. No kidding. It... |
4,306,921 | 4,306,946 | Can I prevent function execution using &=? | Example code follows:
bool result;
result = Operation1();
result &= Operation2();
result &= Operation3();
return result;
The intention is to ensure that, if any of the functions returns false, the functions that follow are not called. Is this syntax correct or do I need to do result = result && Operation2();?
| If you mean a logical "and" rather than bitwise (I suspect so, since you're using a bool), use short circuiting:
result = Operation1() && Operation2() && Operation3();
The functions will be evaluated left-to-right until one of them returns false, then the rest will not be evaluated.
|
4,307,187 | 4,307,737 | How To catch python stdout in c++ code | I have a program which during it's run sometimes needs to call python in order to preform some tasks. I need a function that calls python and catches pythons stdout and puts it in some file.
This is a declaration of the function
pythonCallBackFunc(const char* pythonInput)
My problem is to catch all the python output... | If I'm reading your question correctly, you want to capture stdout/stderr into a variable within your C++? You can do this by redirecting stdout/stderr into a python variable and then querying this variable into your C++. Please not that I have not done the proper ref counting below:
#include <Python.h>
#include <str... |
4,307,240 | 4,335,203 | Using 3rd party library's callbacks (no file descriptor) in an event-driven / asynchronous framework | The goal is to have a single-threaded event-driven framework. The end-user will do something like:
class MyEventFramework : public EventFramework {
protected:
virtual void onData (const Data& data);
virtual void onReport (const Report& report);
virtual void onUserRequest (const UserRequest& userRequest);
...
};
... | If I understand correctly : your dispatching thread is blocked on some system call (say select or poll), and you would like the onData member function to follow the same notification path.
Using a pipe seems like a good solution to me without hurting the design too much :
select monitors one end of the pipe
the 3rd li... |
4,307,271 | 4,307,300 | How to check that the passed Iterator is a random access iterator? | I have the following code, which does some iterator arithmetic:
template<class Iterator>
void Foo(Iterator first, Iterator last) {
typedef typename Iterator::value_type Value;
std::vector<Value> vec;
vec.resize(last - first);
// ...
}
The (last - first) expression works (AFAIK) only for random access iterators... | If Iterator is a random access iterator, then
std::iterator_traits<Iterator>::iterator_category
will be std::random_access_iterator_tag. The cleanest way to implement this is probably to create a second function template and have Foo call it:
template <typename Iterator>
void FooImpl(Iterator first, Iterator last, st... |
4,307,429 | 4,307,534 | Visual Studio: How to specify different runtime libraries for the linker? (/MTd, MDd, etc) | I'm linking to a few libraries in VS2008. If my knowledge of the linker is correct, MTd is for static linking and MDd is for dynamic linking (to a DLL.) My goal is to statically link some libraries and dynamic link others. The project options seems to only have one setting for all libraries in the linker input. How wou... | Your project will be given a sensible C Runtime Library default after you set it up, depending on how you answer the New Project Wizard prompts. You can inspect and alter this (if needed) as follows:
right-click the relevant project in Solution Explorer, select Properties
look under Configuration Properties, C/C++, C... |
4,307,432 | 4,307,506 | Small native cross-platform GUI framework for C++ | I wrote a small program with Boost in c++. It works fine and so I want to give it a graphical interface so that it is easier to use.
In order to do so, I am looking for small cross-platform framework which provides native look and feel. Windows and Linux support would be enough, currently i do not need os x...
I used w... | When it has the word "framework" in its name it's almost never small.
Anyway, graphical frameworks/libraries tend to be big, cause they need to handle a lot of stuff.
Qt is probably the best straightforward library for cross-platform GUI, but it definitely doesn't constitute a "small framework". On the other hand, on L... |
4,307,577 | 4,308,195 | Checked static cast on a reference | Long ago I have created a following template so that I get an assert whenever I perform a static_cast but the type is not what I assume it to be:
/// perform a static_cast asserted by a dynamic_cast
template <class Type, class SourceType>
Type static_cast_checked(SourceType item)
{
Assert(!item || dynamic_cast<Type>(... | Remove * and & from the return types:
/// perform a static_cast asserted by a dynamic_cast
template <class Type, class SourceType>
Type static_cast_checked(SourceType *item)
{
Assert(!item || dynamic_cast<Type>(item));
return static_cast<Type>(item);
}
template <class Type> struct make_pointer
{
typedef... |
4,307,619 | 4,307,668 | How can subclass pointers strictly equal parent class pointers? | I was writing an operator== between two kinds of smart pointer and thought I should run a quick sanity check. I'm suprised by the result...
In the snippet below how is it that all variants of f and b end up with the same value?
struct Foo {
int x;
};
struct Bar : public Foo {
int y;
};
#include <iostream>
in... | About the only time that a base class object won't have the same address as its subclass object is when multiple inheritance is involved.
In the above example memory probably looks like this:
/ --------- \
/ | x | > This is the Foo portion of bar
This ... |
4,307,774 | 4,307,842 | std::map custom key non-uniqueness problem | Couldn't find an answer on Google..
When I use std::string the following works fine.
map <fxString, int> test;
test.insert(pair <fxString, int> ("Bla", 1));
test.insert(pair <fxString, int> ("Bla", 2));
test.insert(pair <fxString, int> ("Bla", 3));
cout << fxInt2String(test["Bla"]) << endl;
Which should output 1, but ... |
"When I iterate through the map every
key value pair is there"
Well, something is wrong with your fxString::operator< then, because the insert member function should have no effect if the key is already present. Are you sure this operator models a strict weak ordering ?
Assuming that the operator is broken, test["B... |
4,308,062 | 4,308,080 | C++ simple file read-in to array question | Simple quick question.
Whats the best way to read in an array of float values that you don't know how long they will be?
(However we know it will not be longer than 75 integers long)
Lets say I have a file (derp.txt)
and the integers are 5.3 6.2 1.5 5.0 1.4 4.5.....etc
and I want to put them into array numbers[75];
Wh... | std::vector<double> results;
std::copy(std::istream_iterator<double>(std::cin),
std::istream_iterator<double>(),
std::back_inserter(results));
You can replace std::cin with whatever stream you are actually using.
It's a bit messier to read into an array, but you probably don't want to use an array ... |
4,308,076 | 4,308,098 | pointer to object == pointer to first member? | Why does the if condition in the following code yield true?
struct A
{
int firstMember;
} a1;
if (&a1 == static_cast<void*>(&a1.firstMember)) std::cout << "equal";
I got a bit confused when reading Stroustrup's FAQ on empty classes, specifically the statement below:
if (p1 == p2) cout << "nice: good optimizer";
| There are no references involved in your code. Don't confuse the "address-of" operator (also &) with references.
Your condition returns true because in this case it happens that the object starts in the same place in memory as its first (and only) field. That's the case i.e. for so-called POD (plain-old-data) objects, ... |
4,308,249 | 4,308,446 | Is there a sleep() function for Android NDK? | Under Android NDK, is there a sleep() function which sleeps for X miliseconds, but do not block the event loop?
We are writing API tests to work on Mac, Windows, and Android. So far, we have implemented some sort of sleep() for Mac and Windows, but we are all new to Android NDK and need some help there. Thank you in ad... | So you are looking for a sleep() method that does sleep for a certain amount of time but does not block the event loop? This sounds odd to me. I think you might want to use a new thread instead and call the sleep() method there - without having to use any JNI.
|
4,308,345 | 4,308,393 | Using C++ class in D | I am trying to find a way to use C++ classes in D.
http://www.digitalmars.com/d/2.0/cpp_interface.html
D cannot call C++ special member functions, and vice versa. These include constructors, destructors, conversion operators, operator overloading, and allocators.
So, I am attempting to dumb down these C++ functions t... | You've not exposed a C interface. You still have your function returning a C++ class rather than something recognizable by C. Expose your class as void *s instead. For example:
class MyClass
{
//private members
public:
//public members
int MyMethod(int argument) const;
virtual float MyVirtualMethod();
virtu... |
4,308,463 | 4,308,483 | Why -1 >> 1 is -1 ? And 1 >> 1 is 0! | I have next code:
std::cout << (-10 >> 1) << std::endl;
std::cout << (-9 >> 1) << std::endl;
std::cout << (-8 >> 1) << std::endl;
std::cout << (-7 >> 1) << std::endl;
std::cout << (-6 >> 1) << std::endl;
std::cout << (-5 >> 1) << std::endl;
std::cout << (-4 >> 1) << std::endl;
std::cout << (-3 >> 1) << std::endl;
st... | Standard 5.8/3 (Shift operators) :
The value of E1 >> E2 is E1
right-shifted E2 bit positions. If E1
has an unsigned type or if E1 has a
signed type and a nonnegative value,
the value of the result is the
integral part of the quotient of E1
divided by the quantity 2 raised to
the power E2. If E1 has a si... |
4,308,474 | 4,308,530 | Help with debugging Qt code | Hi I got couple of questions regarding debugging Qt Code using QtCreator.
I primarily use mac for Qt development but also use win32. So to debug Qt code do I need to install debug library on both?
Say in my application I'm deleting a pointer twice. In small application I can just scan the code and figure out (at le... |
Yes you have to...
I suggest you to use valgrind memcheck. It works on linux and mac (I don't know whether it has windows version) and it replaces malloc and free methods and shows much information about memory handling.
valgrind --tool=memcheck
|
4,308,503 | 4,308,532 | How to enable visual styles without a manifest | According to the docs:
"If you want your application to use ComCtl32.dll version 6, you must add an application manifest or compiler directive to specify that version 6 should be used if it is available."
Notice the logical OR above? So what is this mysterious compiler directive?
I've got a native Win32 C++ application... | If you're using Visual Studio, you can add this line to your stdafx.cpp for example:
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
|
4,308,553 | 4,819,511 | boost::bind encapsulating a HANDLE returned by a COM interface | I have a Visual Studio 2008 c++ project that uses a COM object like this:
ISomeComInterface* foo;
HANDLE file = foo->CreateFile();
// file operations...
foo->CloseHandle( file );
I would like to use boost::shared_ptr<> to encapsulate the lifetime management of the returned HANDLE object. e.g:
ISomeComInterface* foo;
b... | Eric answered the question
#define BOOST_MEM_FN_ENABLE_STDCALL
htttp://www.boost.org/doc/libs/1_45_0/libs/bind/bind.html#Q_com
|
4,308,562 | 4,308,659 | RegisterClassEx Fails as Invalid Parameter - C++ | A call to RegisterClassEx in my application is failing with error code 87, "The parameter is incorrect."
memset( &m_wcx, 0, sizeof(WNDCLASSEX) );
m_wcx.cbSize = sizeof(WNDCLASSEX); // size of structure
m_wcx.style = WS_ICONIC; // initially minimized
m_wcx.lpfnWndProc = &WndProc; // points to window p... | The style member of the WNDCLASSEX structure accepts class styles, not window styles. In other words, you can't make all windows of that class initially minimized that way.
You should pass WS_ICONIC in the dwStyle argument to CreateWindow() or CreateWindowEx() instead.
|
4,308,626 | 4,308,660 | How can I create a common file between JavaScript and C/C++ for a constant? | I have a C++ program with the following in the header file:
#define VARIABLE_X 100
Also, a JavaScript file with the global: VARIABLE_X = 100;
These values will always need to be the same.
Instead of having to change them in both places (.h and .js), I need a common file where both can get this value, thus only needing... | You have an actual script-driven build process, right?
Just stick a rule in your makefile that regenerates constants.h if constants.js has been changed.
|
4,308,758 | 4,308,782 | boost shared_ptr factory function | I'm pretty new to the world of pointers and have run into a problem in my code. I have a factory class that spits out shared_ptr's. "Entity" is the base class for any type of shared_ptr that gets created from this method.
If I overwrite the pointer in the get_entity method, everything seems to work. If i overwrite... | I'm pretty darn confusuled about wtf you're trying to do since you pass in integers to make_shared.
Your problem may be solved by accepting a reference to Entity::EntityPtr in get_pointer.
|
4,308,816 | 4,332,690 | Is a preprocessor needed for a viable language? | How useful is the C++ preprocessor, really? Even in C#, it still has some functionality, but I've been thinking of ditching its use altogether for a hypothetical future language. I guess that there are some languages like Java that survive without such a thing. Is a language without a preprocessing step competitive and... | In fact, most languages deal very well without a preprocessor. I'd move on to say that the necessity of using preprocessor with C/C++ roots in their lack of several parts of functionality.
For example:
Most languages don't need header files and include guards, because they have the notion of a "module".
Conditional co... |
4,308,846 | 4,308,857 | Array Size Not Defined? C++ | Dumb question. but can you do this.
(these are global variables by the way)
int size;
double Values[size];
If Im getting the SIZE from a file?
I know you probably can't, but maybe theirs some way to readjust the size based on the number I read in from the file (like say I read in 7, I know Values will have to be of Si... | No, you can only specify array sizes like this using constant integral expressions. Meaning known at compile-time.
You probably shouldn't be doing this, anyway. Instead, you should be using a vector.
If for whatever reason you can't use a vector (which I would seriously doubt), then your next option would be to use d... |
4,308,912 | 4,309,801 | How to get a sorted subvector out of a sorted vector, fast | I have a data structure like this:
struct X {
float value;
int id;
};
a vector of those (size N (think 100000), sorted by value (stays constant during the execution of the program):
std::vector<X> values;
Now, I want to write a function
void subvector(std::vector<X> const& values,
std::vector<int>... | An alternative approach you could try is to use a hash table instead of a vector to look up ids in:
void subvector(std::vector<X> const& values,
std::unordered_set<int> const& ids,
std::vector<X>& out) {
out.clear();
out.reserve(ids.size());
for(std::vector<X>::const_iterato... |
4,308,939 | 4,309,000 | C++ Line into Vector | Wow I've been all over the place with questions today and I apologize if they seem to overlap, but for every question comes another question...Since one thing wont work......but I should use something else......etc.
Anyways, I have a text file:
6
3.0 2.5 -1.5 0.0 1.7 4.0
6 10
6 is the Number of "floats" in the second ... | something like :
int count, a, b;
double tmp;
std::vector<double> numbers;
ifstream myfile (filename.c_str());
myfile >> count;
for(int i = 0; i < count; ++i) {
myfile >> tmp; numbers.push_back(tmp);
}
myfile >> a >> b;
|
4,309,282 | 4,309,305 | win32: check if window is minimized | How can one check whether a window is minimized using the win32 api?
| use the IsIconic function.
|
4,309,410 | 4,309,704 | C++ Unit Tests, mocking objects | I'm currently looking at some unit test librarys in C++ and have some questions:
there seem to be no mocking facility in boost.test but I can hardly think of doing unit tests without creating mock objects/functions. How would you do that in boost.test, are you doing it manually (how? I mean, there are several ways I c... |
Boost::Test does not have a mocking framework or library. If you want mocks, you have to do it yourself, or use something like GMock. Of course, you could use google mock with Boost::Test without problems.
How else would you expect something to be mockable? That's how it works in every other programming language! (Oka... |
4,309,532 | 4,309,559 | Error C2143 (missing ; before namespace) in MS VC include | I am extremely confused why I am getting this strange error all the sudden:
Time.h is a very simple class, and it has a semicolon at the end of the class description, so I am pretty sure my code is correct here.. Then I get the same errors in: Microsoft Visual Studio 10.0\VC\include\memory.. Any ideas!?!? Thanks!
Compi... | This can happen when one include file has an error (or missing semicolon) at the end of the file and that file is included immediately before another. The error that is generated indicates that there is a problem in the second include file rather than the first. So as a starting point, make sure that, if you have a fil... |
4,309,548 | 4,310,090 | Thread-safe implementation of the Copy-on-write (COW) idiom? | Can anyone point me to a thread-safe implementation of the Copy-on-write (COW) idiom? The sample code on this site looks good -- is it thread-safe?
In case anyone is wondering what I will be using it for: I have a Foo class that has a std::map<int,double> member. Foo objects are copied very frequently in my code, but t... | RcMap's reference counts need to be made atomic in order to be thread safe. In G++ 4.1, you an use the atomic builtins to implement this.
|
4,309,662 | 4,309,824 | Method to remove specific obsolete lines of code from an entire codebase? | I have some code:
#if SILOG
SiAuto.Main.LogException(ex);
// some other lines
#endif
What would be the easiest way to remove surrounding #if from my entire codebase, i.e., end up with just:
SiAuto.Main.LogException(ex);
I'm using Visual Studio 2010. I'll accept the first answer that I can test to see if it wo... | Assuming your codebase is all in one solution file, and you don't have nested preprocessor directives, You can do a find and replace with a regexp:
\#if SILOG{(.*\n)@}\#endif
For the replacement string, use this:
\1
Make sure have are using the "Regular expressions" find option checked.
Step by step:
Open the find a... |
4,309,917 | 4,309,960 | C++ behaviour when const | Here's a basic struct (I hope)
struct SomeType {
float a;
float b;
float c;
float d;
SomeType(float, float, float, float);
};
And source
SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}
The I have a class
struct SomeClass {
static const SomeType v;
... | From what code are you seeing those incorrect values? If it's from something like a constructor of another global variable, remember the static initialization order fiasco; v's constructor might just not have run yet.
Put an output statement in the SomeType constructor and check whether the output occurs before you se... |
4,310,012 | 4,310,381 | Qt tool window resizable on Mac | I have a Qt window with the following flags:
Qt::CustomizeWindowHint
|Qt::Tool
|Qt::WindowCloseButtonHint
|Qt::WindowTitleHint
|Qt::MSWindowsFixedSizeDialogHint
On Mac, it has a resizable corner. How can I get rid of it? Specifying
setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
does not help. In ... | This is in the Qt FAQ.
|
4,310,036 | 4,310,049 | Returning ints versus void |
Possible Duplicate:
What is the proper declaration of main?
A little while ago I took a course on c++ algorithms. We used visual studio in the classroom and sometimes when writing the main function we would declare it void main() { as opposed to int main(){return 0;} . This worked fine although I knew it normally yo... | The standard says that it needs to be int main() (emphasis here on the return type, not the arguments).
void main() is not standard, and as such bound to break on various platforms.
|
4,310,147 | 4,311,664 | Example of code which incorrectly tries to re-seat a reference | As per my understanding, C++ does not allow you to re-seat a reference. In other words, you cannot change the object that a reference "refers" to. It's like a constant pointer in that regard (e.g. int* const a = 3;).
In some code I looked at today, I saw the following:
CMyObject& object = ObjectA().myObject();
// ...... |
I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.
const int i = 42;
const int j = 1337;
const int& r = i;
r = j;
The uninitiated might expect the last line to re-seat r to j, but instead, the assignment ... |
4,310,205 | 4,310,227 | Any library like STL (vector, map...) in C? |
Possible Duplicates:
Container Class / Library for C
Is there a good collection library for C-language?
In C++, you have a very useful Standard Template Library (STL) which has structures like vector, map, set...
If I am using plain C, is there any library provide similar structures/functions?
Thanks!
| glib is an excellent library with many data structures and useful functions. It is used heavily in the GTK+ widget toolkit.
GLib provides advanced data structures, such as memory chunks, doubly- and singly-linked lists, hash tables, dynamic strings and string utilities, such as a lexical scanner, string chunks (groups... |
4,310,277 | 4,310,296 | Producing random float from negative to positive range? | I am trying to produce a random float within the range -50.0 and 50.0 inclusively, using rand(). I've looked everywhere for an answer but it deals with ints and % operator.
| Try this:
float RandomNumber(float Min, float Max)
{
return ((float(rand()) / float(RAND_MAX)) * (Max - Min)) + Min;
}
|
4,310,466 | 4,310,579 | Passing member function to function pointer | I have to pass in a function pointer of a member function to another class. I couldn't get it to compile and I get the "undefined reference to classB::classB(classA::*)(std::shared_ptr) " error. Can someone help me with this?
Thanks.
classA{
string functionA(share_ptr<int>);
void functionB(){
classB* ptr = new... | Just for giggles, going to answer this even though you said it compiled for you ...
// In a.hpp
#include "b.hpp" // you need to include this because you will not
// be able to call B's constructor in your functionB() method
class A
{
public:
string functionA ( shared_ptr<int> ); // IIRC, needs to be... |
4,310,645 | 4,311,139 | How does one setup a pipe between two child processes in Win32? | For the life of me I can't figure out why this is not working. Basically, I created the pipe with the inherit bit set to true, and created two child processes, and used the STARTUPINFO structure to set the input and output handles as one would need, but the pipe seems broken (the second process writes no output to the ... | You misplaced the read and write ends :)
CreatePipe has the prototype
BOOL CreatePipe(
PHANDLE hReadPipe, // can only read from this
PHANDLE hWritePipe, // can only write to this
LPSECURITY_ATTRIBUTES lpPipeAttributes,
DWORD nSize
);
You can't call ReadFile (or in your case std::getline) from a Write-only ha... |
4,310,728 | 4,310,887 | Forcing unaligned bitfield packing in MSVC | I've a struct of bitfields that add up to 48 bits. On GCC this correctly results in a 6 byte structure, but in MSVC the structure comes out 8 bytes. I need to find some way to force MSVC to pack the struct properly, both for interoperability and because it's being used in a memory-critical environment.
The struct seen ... | It is implementation defined how fields will be placed in the structure. Visual Studio will fit consecutive bitfields into an underlying type, if it can, and waste the leftover space. (C++ Bit Fields in VS)
|
4,311,066 | 4,311,140 | Implementing extensible code in C++ | I am currently busy with a project where the main focus of the application is to be extensible (allow 3rd party developers to write plugins / their own implementations of interfaces).
Until now, I have been using Java, and built the application on the NetBeans platform. This has works perfectly fine and is quite easy t... | I recommend that you have a look at the Qt framework. They offer a mechanism to create plugins. Have a look at this free online book about Qt. Plugins are discussed in chapter 21.
|
4,311,182 | 4,311,268 | Low memory image resizing | I am looking for some advice on how to construct a very low memory image resizing program that will be run as a child process of my nodejs application in linux.
The solution I am looking for is a linux executable that will take a base64 string image (uploaded from a client) using stdin, resizing the photo to a specifie... | Depending on the image formats you want to support, it's almost surely possible to perform incremental decoding and scaling by decoding only a few lines at a time and discarding the data once you write the output. However it may require writing your own code or adapting an existing decoder library to support this kind ... |
4,311,261 | 4,311,620 | Of these four libraries, which are you most likely to use? | I'm trying to pick out my next hackery project. It'll likely be one of the following:
A sparse radix trie Implementation with extremely fast set operations
A really good soft heap implementation
A bloomier filter implementation
A collection of small financial algorithms, such as deriving total returns given a set of... | I didn't know what a bloomier (maybe Bloom?) filter is until reading your question. Sounds cool and useful.
|
4,311,352 | 4,311,734 | How do you get a widget's children in Qt? | I'm simulating keyPresses to an application through Qt's KeyPress function. All the KeyPresses work fine. However when I pass a QT::Key_Enter which is supposed to press the OK button of the currently active window, or QT::Key_Cancel for the cancel button, it does nothing.
I'm thinking maybe, because these buttons don'... | You can use the findChild() function with the object name to get a specific child.
You can also use findChildren() to get all the children that have the same name and then iterate through the list using foreach() or QListIterator.
To get a button you can try:
QPushButton* button = pWin->findChild<QPushButton*>("Button ... |
4,311,503 | 4,311,521 | C++ linker cannot find reference to local functions | I have this simple code inserted in myfile.hpp file inside a project of mine:
#ifndef _PERFORMANCE_INDEX_HPP_
#define _PERFORMANCE_INDEX_HPP_
#include <boost/math/special_functions/powm1.hpp>
#include <boost/math/special_functions/log1p.hpp>
#include <boost/math/special_functions/sqrt1pm1.hpp>
//---------------------... | Your functions declarations are in namespace middleware::calculus, your functions definitions are not.
The using declarations you added before the implementations is not of any help here (and is by the way, generally not recommended in a header file), and surely doesn't mean that omitting the namespace in the definitio... |
4,311,808 | 4,311,842 | Project Euler with C++ - compiler won't process after 100 x 101 | I've started working with C++ and was fiddling around with some problems on projecteuler.net.
I'm on question #4 and here's my code:
algorithm to check whether the number is a palindrome:
bool forwardCheck(long posPal){
long n = posPal;
long rev = 0;
long dig;
while (posPal > 0){
dig = posPal % 10;
... | seems that it should be
posPal = posPal / 10
e.g. starting with 123 you want to use 3 for building an inverse number and to move to 12
|
4,311,920 | 4,312,473 | win32 resource file help | on this website, under the "Edit Control" title, there are a couple of lines of code like this..
case WM_CREATE:
hwndEdit = CreateWindow(TEXT("Edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
50, 50, 150, 20, hwnd, (HMENU) ID_EDIT,
NULL, NULL);
hwndButton = CreateWindow(
... | You can create a dialog as your main window.
If you are using MFC in Visual Studio, use the project wizard to create a Dialog-Based app.
(File -> New Project -> Visual C++ / MFC -> MFC Application -> OK -> Application Type -> Dialog based.)
The generated application will then create your main dialog for you, and exit ... |
4,311,953 | 4,311,963 | resizing multidimensional vector | How to resize multidimensional vector such as:
vector <vector <vector <custom_type> > > array;
For example, I need array[3][5][10]?
| You should resize all the nested vectors one by one. Use nested for loops or recursion.
|
4,312,175 | 4,312,208 | How to convert from CString to PCWSTR | I have the following method :
VariantFromString(strXMLPath ,vXMLSource);
and the signature of the method is:
HRESULT VariantFromString(PCWSTR wszValue, VARIANT &Variant);
Now while I am passing a CString as below:
char cCurrentPath[FILENAME_MAX];
if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))
... | You really should be using Unicode (wchar_t instead of char). That is how the OS operates internally, and would prevent having to constantly convert between char types like this.
But in this scenario, you could use CString::AllocSysString to convert it to a BSTR, which is compatible with PCWSTR. Just make sure it gets ... |
4,312,568 | 5,536,329 | What causes WriteFile to return ERROR_ACCESS_DENIED? | We currently face the problem of a call to WriteFile (or, rather CFile::Write - but that just calls WriteFile internally) causing the Win32 error 5 ERROR_ACCESS_DENIED.
(EDIT: Note that we can't repro the behavior. All we have at the moment is a logfile indicating the source line where the CFile::Write was and containi... | The question was
What causes WriteFile to return
ERROR_ACCESS_DENIED?
and I stated in the question
WriteFile will cause
ERROR_ACCESS_DENIED if it is called
for a file handle that is not opened
for writing (i.e. is opened for
reading only).
After adding further logging for the open flags and another inc... |
4,312,679 | 4,312,935 | Is returning a forward-declared structure undefined behavior? | I have the following code (include-guards omitted for simplicity's sake):
= foo.hpp =
struct FOO
{
int not_used_in_this_sample;
int not_used_in_this_sample2;
};
= main.cpp =
#include "foo_generator.hpp"
#include "foo.hpp"
int main()
{
FOO foo = FooGenerator::createFoo(0xDEADBEEF, 0x12345678);
return 0;
}
= ... | That should be fine according to 8.3.5.6: "The type of a parameter or the return type for a function declaration that is not a definition may be an incomplete class type."
|
4,312,827 | 4,312,887 | Pointer instantly 0x0 | i have this code. the pointer turns 0x0 immediately before using it. short before, it had the correct address.
TreeViewColumn *col;
col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
col->set_resizable(true); /* col = 0x0 */
i use Gtkmm 2.4, but it returns the expected value, it just turns 0x0.... | The function call:
preview->get_column(pcFolder);
returns NULL.
When gdb shows the current code line, it hasn't been executed until you type next.
You probably pass an index that is larger than the number of columns in preview. Try:
p pcFolder
p preview->get_columns().size()
|
4,313,113 | 4,313,144 | C++: Access to a public member function from outside of a class | I have a class defined in a separate file and at some point I need to access one of the public member functions from another source file. For some reason, I forgot how to do that and compiler gives me an error.
I have classA.h with definition of class A similar to this:
class classA {
public:
int function1(int alph... | To call a 'normal' function, you need an instance.
classA a;
a.function1(15);
If you want to call the function using classA:: then it needs to be static.
classA {
public:
static int function1(int alpha);
};
//...
classA::function1(15);
Note that inside a static method, you can't access any non-static member va... |
4,313,392 | 4,315,378 | Scenario: Global variables in DLL which is used by Multi-threaded Application | Few months back, I had come across this interesting scenario asked by a guy (on orkut). Though, I've come up with a "non-portable" solution to this problem (have tested it with small code), but still would like to know what you guys have to say and suggest.
Suppose, I created a DLL, exporting some functionalities, writ... |
Can we do something in the client code to prevent multi-access of the DLL, and at the same time, ensuring that each thread runs in it's own context (meaning, when it gets access to the DLL, the DLL's global values are same as it was before)?
This is the hard part. I think the only way top do this would be to create ... |
4,313,449 | 4,615,327 | Eclipse uml to c++ tool? and how to document code? | hi i have two questions about c++ development in eclipse
is there a free tool whitch generate c++ code from UML diagrams?
how must i comment code in c++ that i see the documentation in the tooltip? (in java i write "/**" over the function and press enter and the documentation template is generatet automaic)
| To answer the first point I redirect you to StarUML. This free UML design tool has a C++ add-in that can generate C++ code from the diagrams.
|
4,313,589 | 4,313,644 | Java Process InputStream bug? | Hey guys. So here is the deal. I have a Java program run a C++ program. The C++ process sends some doubles to the Java program by simply calling write on std::cout with some pointer casting. The Java program uses Process's getInputStream(), reads in 8 bytes and converts them into a double using some byte shifting and D... | cout is by default opened in text mode, what I would say is happening is that the 0xa (linefeed) character is getting converted to a <CRLF> sequence during output preprocessing.
I don't think it's possible to reliably write binary data to cout (see here for example), so I would convert your desired output into text, an... |
4,313,678 | 4,313,769 | c(++) union Data structure | I'm programming for a µC, i have following data Structure:
typedef struct
{
RF12Head head;
typedef union
{
uint8_t raw[40];
typedef struct
{
node_id nodeId;
uint8_t hierachyDepth;
} MessageNodeFound;
} data;
} RF12Message;
A RF12Message contains a header an an data part.
Now i w... | You have too many typedefs in your code.
Try this:
http://codepad.org/frysgQte
|
4,313,714 | 4,313,725 | Why do we need to pass LPCTSTR lpParameters with ShellExecute | Shell Execute has the following signature :
HINSTANCE ShellExecute(
__in_opt HWND hwnd,
__in_opt LPCTSTR lpOperation,
__in LPCTSTR lpFile,
__in_opt LPCTSTR lpParameters,
__in_opt LPCTSTR lpDirectory,
__in INT nShowCmd
);
How can we use lpParameters , Can we handle the parameter in my applicat... | lpParameters will come through in the command line. Use GetCommandLine() to see it.
|
4,313,752 | 4,314,394 | Connecting to Boost Signals2 signal with anonymous or lambda function | I am trying to do the following in order to receive a string from a boost signal and post it to the display. The following syntax is incorrect.
signal<void (const char*)> UserMessageEvent;
// connect anonymous boost function to display message box on user message event
UserMessageEvent.connect(bo... | I don't know how boost::bind behave in regard to default parameters.
Anyway, here is the syntax with lambda :
UserMessageEvent.connect( [](const char* message)
{
// maybe need here a conversion to LPCWSTR ?
AfxMessageBox(message);
});
|
4,313,759 | 4,317,240 | Files in folders not found in iOS app using C++ | I'm trying to read files stored in assets folder and its subfolders using std::ifstream in an iOS app written mostly in C++ (The same code is also used in other, non-iOS projects), but they're not found. Example: there is a file assets/shaders/ortho2d.vert and I'm trying to load it like this:
std::ifstream vertFStream(... | Try this:
NSBundle *b = [NSBundle mainBundle];
NSString *dir = [b resourcePath];
NSArray *parts = [NSArray arrayWithObjects:
dir, @"assets", @"shaders", @"ortho2d.vert", (void *)nil];
NSString *path = [NSString pathWithComponents:parts];
const char *cpath = [path fileSystemRepresentation];
std::string... |
4,314,040 | 4,314,090 | Why was function overloading added to C++? | I have a C background. I was just wondering why was function overloading added to C++? C doesn't have function overloading but C++ does, what was the need for it?
What went across the mind of the language designer at that time?
| It increases maintainability. If you have a type T and you call a function with it, then you need to change T, if the function has been overloaded for the new T then you can recompile instantly. In C you would have to go back and dig through all the call sites and change the function called. Take sqrt(). If you want to... |
4,314,060 | 4,315,361 | Tesseract or any other OCR lib | I'm looking for an explanation / API doc / examples of how to use (and train?) Tesseract in C++, nothing useful on the google Tesseract page, and yet to find something over the web.
Anyone useful sources, experiences would be more than welcome, as I have no idea how to begin with it.
P.S:
I'm open for suggestions on ... | I have some experience with Tesseract...
a simple google of 'training tesseract' reveals this page:
http://code.google.com/p/tesseract-ocr/wiki/TrainingTesseract
where you must choose which version of tesseract you wish to train..
While 3 is the latest version, it's brand new and thus people are still ironing out any i... |
4,314,243 | 4,317,752 | Converting FORTRAN to C / C++ | As part of my Final Year Project, I need to convert some FORTRAN code into C or C++ (it doesn't matter which language as long as I can understand it, and I can understand C style languages).
I have discovered f2c, a program that allegedly converts FORTRAN to C, and tried to install it, following instructions, by saving... | I'm going to answer only the very last part of your question:
is there any way of converting that
FORTRAN code into C or C++?
Yes there is: Read the fortran code, and write the equivalent C statements in a C file.
They are both imperative languages. The syntax is different but not impossible to decode. This will... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.