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,989,363
4,990,619
What happens if function inlining is too aggressive?
Each time I read about inline keyword in C++ there's a long explanation that the compiler makes a "speed versus code volume" analysis and then decided whether to inline a function call in each specific case. Now Visual C++ 9 has a __forceinline keyword that seems to make the compiler inline the call to the function unl...
Others have already mentioned the impact on cache. There's another penalty to pay. Modern CPU's are quite fast, but at a price. They have deep pipelines of instructions being processed. To keep these pipelines filled even in the presence of conditional branches, fast CPUs use branch prediction. They record how often a ...
4,989,419
4,989,508
Questions on how compiled programs interact with the operating system
It's been quite some time, I have been programming in C/C++, but some areas still elude me. Perhaps I haven't been reading from well written and authoritative material. (1) In Linux/Unix, is there a limit on how large user programs can be? Maximum size of stack a program can have? Max amount of memory in a heap a user ...
In response to your questions- Most operating systems use virtual memory to have each program think it owns all of the address space. This means that usually the limit on the size of a program is the amount of physical memory in the system, minus a small amount of memory that's usually reserved for invalid (think NUL...
4,989,451
5,154,174
Mutex example / tutorial?
I'm new to multithreading, and was trying to understand how mutexes work. Did a lot of Googling but it still left some doubts of how it works because I created my own program in which locking didn't work. One absolutely non-intuitive syntax of the mutex is pthread_mutex_lock( &mutex1 );, where it looks like the mutex i...
Here goes my humble attempt to explain the concept to newbies around the world: (a color coded version on my blog too) A lot of people run to a lone phone booth (they don't have mobile phones) to talk to their loved ones. The first person to catch the door-handle of the booth, is the one who is allowed to use the phon...
4,989,483
4,989,505
Where to put default parameter value in C++?
What's the place for the default parameter value? Just in function definition, or declaration, or both places?
Default parameter values must appear on the declaration, since that is the only thing that the caller sees. EDIT: As others point out, you can have the argument on the definition, but I would advise writing all code as if that wasn't true.
4,989,561
4,989,616
Memory allocation - Common memory for a process tree
I have to write a code such that, it may create child process via Createprocess API. Parent process in the process tree has to allocate the memory common to the total process tree, so that child process can access it. Malloc, globalalloc does allocate memory within the scope for the process. However I could not extend...
The way to share memory across processes under Windows is through memory-mapped files. Don't be thrown off by the word "file"; there doesn't have to be a file under the memory (other than the swap file).
4,989,592
4,989,638
Change the complex number output format
There is the complex<> template in C++ standard library, and it has an overloaded << operator so that it outputs complex numbers in the (real_part, im_part) format. I need to change the behavior of that operator for complex numbers so that the output format is changed to something completely different. Specifically, I ...
There's no direct way to replace operator <<, but you do have a few options. First, you could just write your own function to print complex numbers: template <typename T> void PrintComplex(const complex<T>& c) { /* ... */ } If you want to still use the nice stream syntax, then one trick you could do would be to m...
4,989,820
4,990,584
Unicode text appears as question marks in edit box, even though I use SetWindowTextW()
I have a problem with unicode filenames appearing as question marks in my edit boxes. When I paste unicode characters in an edit box, for example Arabic or Thai, they show correctly, but after I run this code, they become question marks. How come? WCHAR buf[100]; GetWindowTextW(hWndEditBox, buf, 100); SetWindowTextW(hW...
The GetWindowText function actually sends a WM_GETTEXT message to the window (hWndEditBox). Since you're using the *A functions rather than the *W function (specifically CreateWindowExA in this case, I think) your message loop will be converting from wide characters to multi-byte characters using some locale. Your only...
4,990,045
5,108,972
How to generate type library from unmanaged COM dll
I have to use third party, unmanaged COM dll into my .NET application. I need to modify this assembly to produce a custom RCW. In order to Edit Interop Assembly I need the type library of the particular assembly. Can any one explain me that how to How to generate type library from unmanaged COM dll? There is no option ...
If all you're trying to do is create an Interop Assembly from a native dll (and the native DLL embeds the TLB as a resource), you can just call tlbimp directly on the dll: tlbimp Foo.dll /out:Interop.Foo.dll Which will generate Interop.Foo.dll. You can then use ildasm to modify the IL: ildasm Interop.Foo.dll /out=Foo....
4,990,478
4,990,533
c++: Writing to a file
I have a couple of questions. First, i am doing http byte range requests and then writing the received data to a file. Sometimes, i have to read a block of 1K, and then read that from the file fetched through http. Now, the problem is that the next request after the 1k request may be starting from 100 bytes and in tha...
There's some reference material and sample code on ofstream's seekp at http://www.cplusplus.com/reference/iostream/ostream/seekp/
4,990,562
4,990,672
Efficient way to get first value larger than x in a list?
I have two sorted arrays, Haystack and Needles. I need to iterate over Needles, and each time find the first point in Haystack with a value larger than that Needle, in order to perform the next step. For example: double [] dHaystack = { 1.2, 2.6, 7.0, 9.3, 19.4 } double [] dNeedles = { 1.4, 6.4, 6.5, 7.0, 10.3 } // ...
You need to consider the scenario, n*lg(m) < n+m, Where n is the size of Needle and m is the size of Haystack. Therefore, it all depends on the various combination of values of n and m.
4,990,880
4,994,325
replacing new with macro conflicts with placement new
I've got a massive application (several million LOC, and tens of thousands of files), and I'm trying to use the debug crt to detect memory leaks. I'm trying to macro-ize new like so: #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #ifndef NEW_DEBUG #define NEW_DEBUG new(_NORMAL_BLOCK, __FILE__, __LINE__) #define new NEW_...
You can catch placement new with a variadic macro: #define NEW_DEBUG(...) NEW_DEBUG2(_NORMAL_BLOCK, __FILE__, __LINE__, __VA_ARGS__ ) #define new NEW_DEBUG But the preprocessor doesn't seem to allow defining a macro both with arguments and without, and a macro without arguments is applied first, so I didn't find a wa...
4,990,894
4,990,928
C++ includes and Makefiles
I have a two fold question about working with C++ headers and makefiles. I know that I have all the parts, I am just not sure how to put them together. I have the following files: main.cpp Point.cpp Point.h Point.h declares my simple Point object, the definition is inside the Point.cpp file. Then inside of main() I wa...
Makefiles are nothing more than a way to run certain commands when certain files are out of date. The make program knows next to nothing about C++. You should #include "Point.h" in both main.cpp and Point.cpp. If you want to make sure that make rebuilds your program correctly when you edit files, you should explicitly ...
4,991,267
4,991,326
Why is it allowed to call derived class' private virtual method via pointer of base class?
# include <iostream> using namespace std; class A { public: virtual void f() { cout << "A::f()" << endl; } }; class B:public A { private: virtual void f() { cout << "B::f()" << endl; } }; int main() { A *ptr = new B; ptr->f(); return 0; } This code works cor...
Access control is performed at compile time, not runtime. There's no way in general for the call to f() to know the runtime type of the object pointed to by ptr, so there's no check on the derived class's access specifiers. That's why the call is permitted. As for why class B is permitted to override using a private fu...
4,991,369
4,991,376
Calling Unmanaged C++ code from C#
I have zero experience in C++, but have a few years C# experience. Are there an examples out there showing how I can create a method in a C++ program which is then called from a C# program using the DLL? Cheers
Using p/invoke, you can call C++ code from C#. Read this: Calling Win32 DLLs in C# with P/Invoke Another small yet good article : Using P/Invoke to Access Win32 APIs -- EDIT: This aritcle explains how to create a DLL library in C and then use it with C#
4,991,405
4,991,420
Size of memory allocated on heap
Can you check the size memory allocated on heap if the buffer contains '0' characters? char *c = new char[6]; //random size memory memset(c, 0, 6);
There's no reliable way to do that - you have to store that information yourself. operator new[]() function can be implemented (and replaced by you) in whatever way so you just can't know the size unless you know the exact implementation in details. In Visual C++ the default implementation for built-in types is to just...
4,991,541
4,991,753
std::swap with pointer gives segmentation fault
I have a very simple program but this is giving me a seg fault. I have been struggling from a long time to figure this out. Please help. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <vector> main() { char *database; int ndata=4; database="aaa4baa3bcd2aab5"; char *dummy; dummy=(char *)malloc(16);...
I'll rewrite your code a bit without changing its meaning char *database = "aaa4baa3bcd2aab5"; char *dummy = (char *)malloc(16); memcpy(dummy,database,16); printf("%s\n",dummy); std::swap(database,dummy); dummy[2]='a'; //here you in fact attempt to modify a string literal after you've done swap dummy points where data...
4,991,544
4,991,621
How do you initialize a map that has a priority_queue as a value with the comparison object of the priority_queue?
What I would like to do is have a map that maps integer keys to priority_queues of pointers to a struct I have defined sorted by a comparison function I have also defined. That is, the type would be something like this, map<int, priority_queue<object_t*, compare> > my_map; where you may assume object_t is the my defin...
What is "compare"? If it's a function pointer, you must be very careful to not use it before you supply a value, as the default constructed priority_queue will use a null pointer. The easiest way to ensure non-null pointers – if you cannot rewrite or wrap as shown below – is, ironically, to never use the index operat...
4,991,582
5,146,285
Initializing D3D9 causes a 3rd-party library to stop working
First, the general situation... a 3rd-party library loaded through a DLL does rendering into a HWND. It's simple 2D rendering and is not directly using D3D in a way I can see - a dependency walk on the DLL shows lots of D3DKMT functions like D3DKMTCreateDevice but not regular D3D calls like IDirect3D9::CreateDevice. Wh...
The problem might be that CreateDevice will modify the FPU state unless you pass the flag D3DCREATE_FPU_PRESERVE. It took me a really long time to find this when it bit me.
4,991,638
71,918,895
How to implement C++ (in)equality operators for aggregate structs?
Sometimes I have structs such as this -- struct aggregate1 { std::string name; std::vector<ValueT> options; size_t foobar; // ... }; -- where (in)equality is simply defined as (in)equality of all members: lhs_name == rhs_name && lhs_options == rhs_options && lhs_foobar == rhs_foobar. What's the "best" way to i...
In C++20, implementing equality and inequality operators can be as simple as declaring operator== as default: struct S { int x; // ... // As member function bool operator==(S const &) const = default; // As non-member function (hidden friend) // friend bool operator==(S const &, S const &) = default; };...
4,991,697
4,992,013
Wraps a vector<unsigned char> inside a stream?
I have a function which takes as argument an std::istream& and writes a transformed stream to an std::ostream&. On the another hand, I have another function which accepts a vector argument. My goal is to pass the output of the first function to the second function. Is there something out of the box to do that ? Otherwi...
I think something like this might work std::vector<unsigned char> data; std::istringstream stream_in("input message"); std::stringstream stream_out; functionA(stream_in, stream_out); const std::string& str_out(stream_out.str()); copy(str_out.begin(), str_out.end(), std::back_inserter(data)); functionB(data);
4,991,818
4,992,138
What guarantees are there on interleaved reads and writes?
When working with a C++ std::iostream (for example, std::fstream or std::stringstream, does the standard guarantee anything about the relationships between reads and writes performed on the same stream? That is, is it necessarily true that if I write data into a std::fstream, then try reading data out of that stream, ...
I am not sure about the chapter and verse of the C++ standard (which I don't have around to check), but I am very familiar with the C standard on the subject (which I do have around). C99 states that a stream can be opened in read, write, or "update" mode. Only the latter mode allows both reading and writing to the sam...
4,992,024
4,992,052
Bit-level endianness
How to check the 'endianness' of OS at bit-level or Does an OS even care in what order the bits are stored?
char is the smallest addressable unit of memory, so you don't care what happens beyond that level - you can't read/write less than char anyway, hence the idea of "endianness-at-bits-level" makes no sense.
4,992,106
5,039,736
Dissapearing radiobutton on Windows Classic theme
my application has standard controls - textboxes, statics, and a few option buttons (radio buttons). When windows theme (XP) is set to "Classic", and user presses TAB on the form, radio buttons disappear, that is, they are not drawn. Dragging something over my window redraws them. Any ideas?
I will quote your own answer here Marin, so that the question no longer appears to have zero solutions, hope you dont mind :) Quote: resolved, frame had empty spaces as text, and windows misbehaves on classic theme in this case. – Marin yesterday
4,992,229
4,992,260
Spaces cant be used in string? c++
Basically I'm experimenting with polymorphism. I have 2 objects, a customer and an employee. a customer has a name and a complaint. An employee has a name and a salary. In a loop, I take in these parameters and create a new Person to add to an array. But here's my issue: If I put any spaces in the string, the loop race...
The input operator std::istream& operator>>(std::istream& is, std::string&) only ever reads input up to the next whitespace character. (That's just the way it was specified when Jerry Schwartz invented IO streams 25 years ago.) If you need to read whole lines, then std::istream& getline(std::istream&, std::string&,...
4,992,247
4,992,281
How is compilation unit defined in c++?
Possible Duplicate: What is a “translation unit” in C++ It is often said that the static variables declared in C/C++ are not visible across compilation units ? Does this mean that each .c or .cpp file is a seperate compilation unit ? What about a ,h file and the static variables declared in the .h file ? Is .h file...
Header files have no separate life, only their content is #included into .c or .cpp files. But since #include is handled by the preprocessor, the compiler has no knowledge about distinct header files; it only sees the resulting code listing as input. This is what is called a compilation unit: a source file with all its...
4,992,307
4,992,378
Factory Pattern in C++ -- doing this correctly?
I am relatively new to "design patterns" as they are referred to in a formal sense. I've not been a professional for very long, so I'm pretty new to this. We've got a pure virtual interface base class. This interface class is obviously to provide the definition of what functionality its derived children are supposed to...
You do NOT want to use your interface class as the factory class. For one, if it is a true interface class, there is no implementation. Second, if the interface class does have some implementation defined (in addition to the pure virtual functions), making a static factory method now forces the base class to be recom...
4,992,412
5,016,835
my Dll size blown out by introducing large switch cases, how can I reduce my Dll size(MSVC C++)?
My Dll size is of 2 MB. Now I have a situation where I need to add a switch case with 2500 case arms.. each case invoking a function. So total 2500 different functions are being called through this switch case with 2500 cases in it. (The entire code for 2500 functions is already exist in the DLL of 2MB. Extra code incl...
With The intial trials i came to conclusion that theres nothing much when we try with Function pointers.. i found contiguous switch cases and function pointers are almost same as per my requirement where as maps are blowing my Dll size abit more. Here the issue is not with the switch cases as i thought but with the c...
4,992,442
4,993,880
C/C++ detect network type
I need to write a win32 c/c++ application which will be able to determine whether the PC it's running on is connected to one of 2 networks. The first network is the company LAN (which has no internet connection) and the second network is a standalone switch with a single PC connected to it (the PC that the program is ...
I would first try to differentiate between the two using information available locally--that is, from your computer. Does the output of ipconfig /all differ depending on which network you're connected to? If so, exploit that difference if you can. Is it possible to get the MAC address of the standalone switch? Of th...
4,992,448
4,998,674
C++: possible Xcode (Mac) problem. Can't read in numbers from external file using getline()
I'm a Mac Xcode (3.2.2) user, working with the GCC 4.2 compiler, fairly inexperienced with C++ and completely ignorant about compilers. I need to read in numbers from an external file and store them in a vector of ints. I wrote code using streams and getline(). I can compile the code and it runs without errors, but the...
This might work for you. It uses getline as you were trying, but uses the '\'' character to serve as the line delimiter. Ignore everything up to the first '. Assume everything until the next ' is part of a number. Continue until the logic fails (presumably due to end of file). #include <fstream> #include <iostream>...
4,992,507
4,995,202
Image slider for c++
I have c++ program which display images, I want to move from one image to another, with nice effect Do you know any project that can help me? (For example se the effects inside http://www.youtube.com/watch?v=Z6PR9AM1vsA much less than that will be acceptable.) Thanks. ---------------Edit------------------- I am using w...
Here's an image viewer with some of the features you're looking for. It didn't get the best reviews, but it may help you get started. Built in VC++/MFC.
4,992,690
5,074,390
how to display large data in wxListCtrl with using concept of wxThread
I'm capable to fill the database table in wxListCtrl, my problem is to handle high range of data, I want to do this with the help of thread concept , perhaps it will save to hang the frame because of high amount of data. I'm new in thread concept so your single lines will be a book for me. Update: My question was- how ...
When you are performing high range of data you are bound to use WXThread in your program Firstly was trying to fill wxListCtrl from wxEntry point, it was wrong u can not hit any main thread control from entry point, it does not give error, but it is a wrong concept Here u need to pass the data to handler, handler wil...
4,992,926
4,993,058
How to find whether a string is guid in c++
How to find whether a string is guid in native c++? a code sample would help greatly
If you need to do it by hand (information from wikipedia): Check the length (36, including hyphens) Check that the hyphens are at the expected positions (9-14-19-24) Check that all other characters are hexadecimal (isxdigit)
4,992,989
4,994,811
How do languages handle side effects of compound operators?
Assume such situation: int a = (--t)*(t-2); int b = (t/=a)+t; In C and C++ this is undefined behaviour, as described here: Undefined behavior and sequence points However, how does this situation look in: JavaScript, Java, PHP... C# well, any other language which has compound operators? I'm bugfixing a Javascript -> ...
According to the ECMA Script specification, which I believe javascript is supposed to conform to, in multiplication and addition statements, it evaluates the left hand side before evaluating the right hand side. (see 11.5 and 11.6). I think this means that the code should be equivalent to t = t - 1; int a = t * (t - 2)...
4,993,101
4,993,646
Is C++ SDL and (Python PyGame) used by people other than hobbyists?
As a hobbyists who has a little experience making 2D games using PyGame, and has ventured into using C++ with the SDL library (in Visual Studio), I'm curious. Is the library used professionally?
http://en.wikipedia.org/wiki/List_of_games_using_SDL Doom3 and Unreal Tournament are on that list, so I'd say it is used professionally
4,993,181
4,993,827
Creating DLLs in C++
This is a follow-up question to this question because I'm losing my mind over this right now. Someone pointed me to this article and I'm trying to copy section 4 from there. So I created an empty C++ Project in MSVC++2010, created a new .cpp file inside it, and put the following code in there: #include <windows.h> #def...
Maybe your vb6dll32.dll is dynamically linked and depends on stuff like MSVCR100.dll, which isn't easy to locate. Check imports and put these dlls beside your vb6dll32.dll, or link it statically (/MT /LD). Also you really don't need these CODE and DATA lines in the .def file.
4,993,294
4,993,982
Win32 threads dying for no apparent reason
I have a program that spawns 3 worker threads that do some number crunching, and waits for them to finish like so: #define THREAD_COUNT 3 volatile LONG waitCount; HANDLE pSemaphore; int main(int argc, char **argv) { // ... HANDLE threads[THREAD_COUNT]; pSemaphore = CreateSemaphore(NULL, THREAD_COUNT, THRE...
How do I debug weird thread behaviour? Not quite what you said, but the answer is almost always: understand the code really well, understand all the possible outcomes and work out which one is happening. A debugger becomes less useful here, because you can either follow one thread and miss out on what is causing othe...
4,993,516
4,997,380
directshow disable activemovie window in C++ console application
I am creating a video frame output program in a c++ console application using direct show. I have the video loading in and playing fine, however, the video pops up in an ActiveMovie Window. Is there any way I can possibly disable this that way I can just output frame information to the command line window? Thanks in ad...
What kind of frame information do you want to output to the console? To not have the ActiveMovie video popup, you could just use the null renderer filter.
4,993,518
4,995,675
array[byte] to HBITMAP or CBitmap
I have an array of bytes (which I read through a stream directly from a .bmp and then store as a BLOB in a database) which I want to display as icons in a CImageList. Therefore I want to somehow load my data into an HBITMAP or CBitmap. I have done it like this up to now, reading from a file: hPic = (HBITMAP)LoadImage(N...
Assuming you have the information loaded into a BYTE array named bytes.... BITMAPFILEHEADER* bmfh; bmfh = (BITMAPFILEHEADER*)bytes; BITMAPINFOHEADER* bmih; bmih = (BITMAPINFOHEADER*)(bytes + sizeof(BITMAPFILEHEADER)); BITMAPINFO* bmi; bmi = (BITMAPINFO*)bmih; void* bits; bits = (void*)(bytes + bmfh->bfOffBits); HDC ...
4,993,613
5,042,449
calling C++ "int WINAPI _tWinMain" from C#
I can access a method from a C++ Dll using C# using this method in the C++: extern "C" { __declspec(dllexport) void DisplayHelloFromDLL() { printf ("Hello from DLL !\n"); } } this works great...but the solution I am working with uses this as the entry point: extern "C" int WINAPI _tWinMain(HINSTANCE hInstanc...
The answer was to call a function created in the C++ using: extern "C" { __declspec(dllexport) void StartAgent() { printf ("Starting Agent... \n"); StartServer(true); RunMainLoop(); } } This is then called in the C# using: [DllImport("myDll.dll")] public static extern string StartAgent(); StartAgen...
4,993,650
4,993,681
What is sizeof(something) == 0?
I have a template that takes a struct with different values, for example: struct Something { char str[10]; int value; ... ... }; And inside the function I use the sizeof operator: jump in memory sizeof(Something); Sometimes I would like to not jump anything at all; I want sizeof to return zero. If I pu...
sizeof will never be zero. (Reason: sizeof (T) is the distance between elements in an array of type T[], and the elements are required to have unique addresses). Maybe you can use templates to make a sizeof replacement, that normally uses sizeof but is specialized for one particular type to give zero. e.g. template <t...
4,993,959
4,993,999
Vector indexing for short
Suppose I have a vector std::vector<a> A; I can get access to its member-functions through the . operator and I can index it with the [] operator. If I have a pointer to a vector, e.g. std::vector<a> *A; I can get to its members using the short -> operator, but indexing is very inconvenient, i.e. (*A)[i]. How can it be...
Bind it to a reference is the easiest way if (*A)[i] is a problem: std::vector<a>& ref = *A; ref[i] = 0; //use reference Normally I'd prefer passing vectors by reference instead of pointer anyway unless you really want to allow NULL values too.
4,994,017
5,027,061
Property page for custom Directshow filter
I managed to create a custom DirectShow transform filter, register it, and export it in a DLL. It now works properly in both GraphEdit and a C++ test program. My next goal is to create a custom interface to control the filter's main parameter, from a test app or from a property page in GraphEdit. Following these instru...
Looks like the problem came from the way I was creating the controls for the Property Page. I use a simple "Formview" resource, but I was trying to add the controls through the graphical resource viewer (or whatever you want to call it) : right click, "Insert ActiveX Control..." and using "Microsoft Form 2.0". Using a ...
4,994,031
4,994,065
Comparison (operator's overloading) of large and sophisticated structures in c++
We must face serious issue while prepraing my project and working on code in c++. My code is build on multiple structures/classes where one is included in another. Finaly i will have to compare all these structures between themselves. In this case it is impossible (or requres terrible effort) to overload comparison op...
If you can implement a common interface in each of the classes that provides the tools necessary to compare the various different classes. In this way you can write just one single operator== which operates on the interfaces without needing to know about the low level details.
4,994,077
4,994,706
Boost async_write problem
i'll show some piece of code ; void wh(const boost::system::error_code& ec, std::size_t bytes_transferred) { std::cout << "test"; } int main(int argc, char* argv[]) { boost::asio::io_service pService; boost::asio::serial_port pSerial(pService,"COM4"); while (true) { boost::asio::asyn...
You're not using async_write correctly. It is a composed operation, and it's up to the application's responsibility to ensure no other calls to async_write on pSerial are made until the write handler is invoked. The documentation summarizes this nicely This operation is implemented in terms of zero or more calls to ...
4,994,128
4,994,236
Deploying C# application with UAC
We are creating a C# .net application, which uses a .dll file developed in C++. It also requires some user controls developed by a third party (bundled as .dll with the application.) If we run this application on a machine with UAC enabled, it executes as expected. However, if we deploy it using an installer created th...
Obviously, you cannot run as administrator without the UAC prompt. That would make life too easy for malware writers. I suspect the location where it's installed matters. Usually that's under \Program Files\, and that's also its default working directory. However, the program may not write there when ran under a non-ad...
4,994,257
4,994,412
set a member attribute in a "generic" way
Is it possible to set a member attribute in a "generic" way? I am still new to c++ and just dived into templates, if this is the way to go? The class i have to use has around 20 string members to be filled from informix database and i could loop through an array with the field(=attribute) names. Let's say i have a si...
You can use member data pointers. These can be of any type- e.g. struct x { int y; int z; }; int main() { int x::* res = &x::y; } However, if you want to start accessing them by identifier at runtime, you will have to build your own system from scratch.
4,994,388
4,994,448
C++ is_trivially_copyable check
How to check whether or not C++ type is trivially copyable? I have a class, which uses memcpy and memcmp functions with specified template type T and I would like to fire assert for types, that are not safe to copy with memcpy. Is there any way to do that (with existing standard)?
No, not possible in C++98/C++03. Things like this are why <type_traits> was added to C++0x. Some of the features from <type_traits> can be implemented in C++03, often using the SFINAE principle, but several, including std::is_trivially_copyable<T>, will simply require built-in compiler support.
4,994,660
4,994,718
Async C++ Communication Library for Linux (and Windows)
I'm looking for a communications library (socket, possibly IPC as well) for usage in C++ on Linux, if possible also on Windows if it's platform independent. It should be async. I tried the Boost Asio Library, but due to limitations we can't find a solution for, we cannot use the Asio library in our solution. It should ...
Take a look at ZeroMQ, a.k.a ØMQ.
4,994,775
4,995,094
C++ specialization of template function inside template class
What is the C++ syntax for specializing a template function that's inside a template class? For example, consider that I have the following two classes and their usage. I would like to be able to provide specialized implementations of the method X::getAThing() for different types. E.g.: int, std::string, arbitrary p...
So, I'm taking a different approach to answering your question. I'm going to start from something that sort of does what you want, and works. And then maybe we can figure out how to permute it into something closer to what you really want: #include <string> #include <iostream> int getIntThing(const ::std::string &para...
4,994,850
4,994,943
Standard vector and boost array: which is faster?
How the performance of boost::array compares to that of std::vector, and which factors have significant influence on it?
boost::array (or C++0x's std::array) should be faster than std::vector because boost::array instances are entirely on the stack. This means boost::array has no heap allocation, and it also means it can't grow past the size you specify for it at construction. The purpose of boost::array is to serve as a thin layer aroun...
4,995,000
4,995,035
Problem with linking one file containing namespace definition with another using that namespace in C++?
I have two files once is named as test.cpp and another as ani.cpp. test.cpp is as follows: #include<iostream> namespace Anirudh{ void start(){ std::cout<<"This is the start function of the namespace Anirudh\n"; } } and the file ani.cpp is as follows #include<iostream> using namespace Anirudh; int ma...
Within ani.cpp you never told the compiler that there's a namespace Anirudh somewhere else in the program prior to doing the using. If you're used to other module systems this probably seems quirky. What you can do is declare the namespace+function prior to calling it, with these lines before the using namespace in ani...
4,995,258
4,995,322
Can we detect empty classes in C++03?
Possible Duplicate: Is there an easy way to tell if a class/struct has no data members? Can we detect emply classes, possibly using template? struct A {}; struct B { char c;}; std::cout << is_empty<A>::value; //should print 0 std::cout << is_empty<B>::value; //should print 1 //this is important, the alleged duplic...
If your compiler supports the empty base class optimization, yes. template <typename T> struct is_empty { struct test : T { char c; }; enum { value = sizeof (test) == sizeof (char) }; }; template <> struct is_empty<int> { enum { value = 0 }; }; Better: #include <boost/type_traits/is_fundamental.hpp> temp...
4,995,260
4,995,360
Issue passing C-Strings in C++
I'm not C++ developer and I'm trying to figure out why when I return a C-string from a function I'm getting garbage out. #include <stdio.h> const char* tinker(const char* foo); int main(void) { const char* foo = "foo"; foo= tinker(foo); printf(foo); // Prints garbage return 0; } const char* tinker(co...
To add to what others said, this is one way to get it to work: #include <stdio.h> std::string tinker(const char* foo); int main(void) { const char* foo = "foo"; std::string foo2= tinker(foo); printf(foo2.c_str()); // Prints correctly return 0; } std::string tinker(const char* foo) { st...
4,995,378
4,995,502
C++ Template for mapping struct type to enum?
I have something like: struct A { ... }; struct B { ... }; struct C { ... }; class MyEnum { public: enum Value { a, b, c; } } template<typename T> MyEnum::Value StructToMyEnum(); template<> MyEnum::Value StructToMyEnum<A>() { return MyEnum::a; } template<> MyEnum::Value StructToMyEnum<B>() { return MyEnum...
The multiple definitions are because you need to either add the inline keyword or push the implementation of your specializations into a cpp file, leaving only the declarations of such in the header. You could probably use mpl::map to write a sort-of generic version. Something like so: struct A {}; struct B {}; struct...
4,995,995
4,996,031
Concat'ing intergers to make a string
This is what I am trying to do: int x = 0; char toBuffer; while (twenty_byte_buffer[x] != '\0') // While the string isn't at the end... { cout << int(twenty_byte_buffer[x]); // show me, works fine //need to concat the int values from above into toBuffer as a string //eg. "-62-8711097109" would have derived from this "...
Use a stringstream. It works just like cout: stringstream sstr; while (twenty_byte_buffer[x] != '\0') { sstr << int(twenty_byte_buffer[x]); x++; } string result = sstr.str();
4,996,692
4,996,792
const variable in c++
these are the some silly question ..i want to ask..please help me to comprehend it const int i=100; //1 ///some code long add=(long)&i; //2 Doubt:for the above code..will compiler first go through the whole code for deciding whether memory should be allocated or not..or first it ll store the variable in read only...
In your code example, add contains the address, not the value, of i. I believe you may have thought that i was not stored in normal memory unless/until you take its address. This is not the case. const does not mean the value is stored in ROM. It is stored in normal memory (often the stack) just like any other variable...
4,996,927
4,997,065
File I/O across processes in Linux?
So, I've got a Linux process where I'm trying to manage some files on a tape. I have the following code that attempts to extract a file, catalog.xml, from the current archive on the tape and copy it to a fixed location (eventually, I'll parse the file and do some work with the results). But, my code is intermittently...
If execlp succeeds, it will never get to the line where you call _exit. You aren't checking the return value (ret) from wait. It's not clear why you should be using vfork. Etc. Since the parent is not doing anything else besides waiting for the child to complete, why not make your life easier and just use system()?
4,996,960
4,997,348
How I can work with Excel 2007 and Excel 2003 (Excel Chart) from win32 application using COM?
How I can work with Excel 2007 and Excel 2003 (Excel Chart) from win32 application using COM? Where I can see any examples (for Visual Studio 2003) or manual of this problem?
Using #import, you can get VC++ to generate lots of smart pointer code for interacting with COM. This is my preferred method for Office automation from C++. Add this to the top of your source file to generate the files and include the appropriate generated files: #import "C:\\Program Files\\Common Files\\Microsoft Shar...
4,997,088
4,997,123
C++ vs C for distributed computing
I am about to start a new project in scientific computing, which will run on a computer cluster using from 8 up to 32 CPUs. I will use MPI to distribute the calculations. The last thing is which language is better to use C or C++? I will do some serious number crunching, and I will need a smooth and well-distributed pa...
You can write slow code in any language. MPI is a message-passing library so it simply does not care whether you call it from C or C++ --- use whichever language you are better at. Which you should determine by profiling and measuring. The Language Shootout comparison between C and C++ is pretty even about size, sp...
4,997,363
4,997,412
STL BigInt class implementation
Does STL have a BigInt class implementation? (numbers with many digits held into a container)
The C++ standard library (sometimes erroneously referred to as "STL") does not contain any extended precision support.
4,998,156
4,998,167
How to comment C++ code so that comments would be visible in IntelliSense
In C# if I want to comment a function I just press / three times and appropriate tags appear above a function. Everything I write in this tag is then shown in IntelliSense so I can easily see what the given function does. However in C++ there is no such tags, so how can I comment code so that my comment would be recogn...
You can still use /// in Visual C++ - the IDE doesn't give you the template XML though.
4,998,344
4,998,412
Why must a pure virtual destructor's implementation be empty? And should it be inline?
I read in other threads that when you implement a pure virtual destructor (yes it can have an implementation) it must be empty, and should (?) be inline. Should it be empty? If so, why? Should it be inline? If so, why? Edit: This is how a pure virtual descructor can have an implementation: class A{ virtual ~A() =...
A pure virtual destructor must have an implementation (assuming you have at least one concrete derived class). There is no rule that a pure virtual destructor must have empty body. Nor do I know of any reason that it should, except the same reasons most destructors should have an empty body. A pure virtual destructor ...
4,998,495
4,998,583
C++ Command line action abstraction using interface
I'm building an application whose usage is going to look something like this: application --command --option1=? --option2=2? Basically, there can be any number of options, but only one command per instance of the application. Similar to the way git works. Now, I thought I'd write it in C++ to get some boost and stl ex...
One thing than needs to be said right off the bat is that runtime polymorphism works in C++ via pointers to the base class not by value. So your std::map<std::string, Action> needs to be std::map<std::string, Action*> or your derived Actions (i.e. DisplayHelpAction) will be sliced when copied into the map. Storing Act...
4,998,512
4,998,570
Standalone VS 2010 C++ Program
it's been a long while since I've used VS 2010 and C++, and as I'm getting back to using it, I'm running into the same problems that plagued me last year: the exe's that I compile do not run well on older machines that do not have the correct C++ runtimes. I do not even know what link to give them, and I told them to i...
The easiest thing to do is to just install the VC++ Redistributable Package. It has both x86 and x64 versions.
4,998,597
4,998,654
Overload <<, returning ostream gives error. C++
I'm having an issue with overloading the << operator. Everything prints and enters fine, but when I try and return the ostream, I get this error: Expression: _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) I've also already overloaded another << operator in this project that has returned an ostream just fine. This operator isn...
There's nothing in the shown code that will cause the problem you describe. The "_BLOCK_TYPE_IS_VALID(pHead->nBlockUse)" error is an indication that the heap was corrupted at an earlier point, it's being detected at your return statement but isn't otherwise related to the code in your operator<<
4,998,627
4,998,657
Writing a merge method for lists
I'm trying to write a method that merges a doubly linked list in an alternating fashion. So if we have two int lists (0,1,2,3) and (4,5,6), we'd just have one final list of (0,4,1,5,2,6,3). Each list has a head, a tail, a next, and a prev pointer. Its hurting my mind to try to figure out where to start or how this wou...
Create a third, empty list (called the "result list"). Loop while there are still elements left in one of the lists: If the first list is not empty, pop an element off the front of the first list and push it onto the back of the result list. If the second list is not empty, pop an element off the front of the second...
4,998,790
4,998,905
How to deduce array size from an enum template argument?
How should I change the code below so that Array<Index> array; is enough and the SIZE is automatically deduced from the enum? Even if the enum changes, it is guaranteed that it contains SIZE referring to the correct size. template <typename Enum, int N> class Array { public: int& operator[](Enum index) { return ar...
You can write a traits class. This requires a bit of extra work each time you define a new enum type, but no extra work for each occurrence of Array<Index> in user code: template<class Enum> struct ArrayTraits; template<class Enum> struct Array { int& operator[](Enum index) { return array[index]; } private: int ...
4,998,814
4,999,186
CreateFile GetFileTIme SetFileTime
I'm having trouble using GetFileTime and SetFileTime when it comes to directories. Specifically I think my problem is that I am new to the WinAPI and I don't think I'm getting the HANDLE correctly. There are 2 scenarios. In the first, I just need a handle to get the file or directory timestamps (create,access,mod)....
Answer #2: To use CreateFile to get a handle to a directory, you need to use the FILE_FLAG_BACKUP_SEMANTICS flag. Using your example: h1 = CreateFile(itemA, GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0); I would guess this would work for Answer #4 as well, but I haven't tried it to c...
4,999,099
4,999,509
Form input validation, multiple focus issues
I am having an issue trying to validate some input in QT4. I have a form with 2 textEdit fields. When one field loses focus, I want it to check if the field is empty, and if so, alert the user. Here is my code: void newconsole::on_nameEdit_lostFocus() { if (this->ui->nameEdit->text().size() < 1) { QMes...
my guess would be: your edit boxes are positioned close to each other on the form or/and next to each other in the tab order; both edit boxes are empty by default; when you're moving focus from the empty nameEdit to the next widget which is fileextensionEdit, first message box pops up; this message box causes fileexte...
4,999,241
4,999,832
mixing use of constexpr and const?
I read a little of CLang implementation of standard library and it confuses me a little bit on const and constexpr. template<class _Tp, _Tp __v> struct integral_constant { static constexpr _Tp value = __v; }; template<class _Tp, _Tp __v> const _Tp integral_constant<_Tp, __v>::value; What makes me confusing is tha...
S::size is not a constant expression according to N3225 §5.19p2: A conditional-expression is a constant expression unless it involves one of the following… an lvalue-to-rvalue conversion (4.1) unless it is applied to a glvalue of integral or enumeration type that refers to a non-volatile const object with a pre...
4,999,401
5,012,298
Hiding the Cursor / Warp Mouse (SDL 1.3)
I've been unable to hide the mouse cursor (properly) using SDL. I am using Ubuntu 10.10 and have been using the following: SDL_ShowCursor( SDL_DISABLE ); SDL_WarpMouse( x, y ); Neither of which function properly at all; it would appear to have no visual effect, there is however a triggered mouse motion event as the ...
*Yes, cursors are not yet implemented in SDL 1.3. I'm sort of intentionally leaving them unimplemented as a reminder that 1.3 isn't ready yet. * Quote by Sam Lantinga, an SDL Developer; therefore this question is simply an SDL bug (soon to be fixed).
4,999,404
4,999,419
C++ Void Function Confusion
I'm working on a homework assignment and I'm confused about what the directions want me to write for these functions. The directions say: Write a void function called GetSalesInfo that accepts the following as input from a user Account Number Date of Sale County Code Total Sale Shipping Weight This function sho...
Well, it specifically calls for a void function which means it will return nothing via the return value. C++ has reference types which augment the C way of doing it (passing in pointers to the variables then dereferencing them to change them outside the function): void GetSalesInfo (int &accNum, int ...
4,999,439
4,999,695
Combo being editable C++
I have a combo in my UI application which must not be editable. In other words I have few items in the drop down combo and user mus tbe able to drop down the combo when clicked anywhere on the combo. However somehow when i click on the arrow only the combo drops down. If I click anywhere in the combo the field becomes ...
In the resource editor in VS, bring up the properties for the combo box. Change the "Type" property to "Drop List". This is the GUI equivalent to the CBS_DROPDOWNLIST style that anand mentioned.
4,999,492
4,999,546
How to determine where a memory leak occurs in C++?
How to determine where memory leak is, in C++ not by using any tools I have a memory leak in my program, and I am trying to determine where it is leaking. If you can shed any light on this subject please do.
Since the question (now) says "not using any tools", then you are probably reduced to looking at the source code. One place to look is at the constructors and destructor of each class. Is all the memory allocated by your constructors released by your destructor? If other methods in your class allocate memory, is that...
4,999,542
5,000,258
read data from text file
2 1 3 6 0 9 0 2 9 5 0 0 8 3 10 0 6 0 6 3 1 1 0 4 0 8 2 1 7 0 0 8 3 5 0 4 0 5 4 1 3 10 0 0 7 2 5 7 0 2 0 ...
The simpler and more efficient way would be to scan the file character by character, i.e increment "i" aand compare for each value. if(i==" ") // if the character is " " SPACE then do nothing /\/\ if(i==10) // if the character is ascii(10) i.e ENTER then switch to col01 /\/\ else go on storing the DIGITS in col01, then...
4,999,588
4,999,669
Output iterator that only counts the number of increments?
In STL/Boost, is there a ready-made output iterator that only counts the number of times it's incremented? When an algorithm does *iter = value, the value would simply be discarded. If not, then rolling my own seems easy enough. Although it might be useful to others if someone posted an example of such an iterator.
No such iterator exists in standard C++, and to the best of my knowledge no Boost iterator has this exact functionality. There are plenty of ways that you could do this using those libraries without having to roll your own, though. For example, using Boost's function_output_iterator, you could build a counter like th...
4,999,603
4,999,649
If a class might be inherited, should every function be virtual?
In C++, a coder doesn't know whether other coders will inherit his class. Should he make every function in that class virtual? Are there any drawbacks? Or is it just not acceptable at all?
In C++, you should only make a class inheritable from if you intend for it to be used polymorphically. The way that you treat polymorphic objects in C++ is very different from how you treat other objects. You don't tend to put polymorphic classes on the stack, or pass them by or return them from functions by value, s...
4,999,650
4,999,719
C++: how do I check if the cin buffer is empty?
How do you check to see if the user didn't input anything at a cin command and simply pressed enter?
When reading from std::cin, it's preferable not to use the stream extraction operator >> as this can have all sorts of nasty side effects. For example, if you have this code: std::string name; std::cin >> name; And I enter John Doe, then the line to read from cin will just hold the value John, leaving Doe behind to ...
4,999,796
4,999,829
unresolved external symbol "cSocket::cSocket(void)" in function _main
#ifndef _ClientSocket_H_ #define _ClientSocket_H_ #include "Includes.h" #include "LOGMSGs.h" class cSocket { public: cSocket(); bool Open(); bool Listen(char *OnIP,int OnPort); void Send(char *MSG, int len); void Recv(char *MSG,int len); void Close(); protected: SOCKET cSock; const in...
This is a linker error, which means that the compiler has checked that the code contains no syntax errors, but the linker can't find an implementation of a function you've tried to call somewhere in the program. In this case, the function it can't find is __thiscall cSocket::cSocket(void)" (??0cSocket@@QAE@XZ) This ...
4,999,822
5,001,055
Changing the text Colour in a ListView Control ( Win32)
I have a List View Control that I have created with Win32 C++ I am adding sub items using ListView_SetItem This just Text and the List View is in Report Mode. I want to change the colour of the text for a particular sub Item . Can I do this? How Thanks
You'll need to use owner-draw for this sub item so that it uses different font properties than the rest of the list view.
4,999,907
4,999,937
find same node from two single linked list. Can't use hash, Can not be O(n^2) complexity
find same node from two single linked lists. Can't use hash, Can not be O(n^2) complexity. Please give some hints. thank you so much.
Sort the two linked lists and then do a linear pass to find two nodes that are equal. This is 2*O(NlogN) + 2*O(N) = O(NlogN).
5,000,109
5,000,381
Implement double sqrt(double x) in C++
Implement double sqrt(double x) in C++ without using std library. This is a facebook interview question I saw here. http://www.glassdoor.com/Interview/Implement-double-sqrt-double-x-in-C-QTN_87210.htm Any other good idea about this?... !!!Edited.!!!(without using std library.)
Look here. This CodeProject article compares 14 different methods for computing the square root.
5,000,159
5,000,224
Initialize a class with constructor inside a header
i´m having this error. My header: libtorrent::fingerprint a("LT", LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0); class TorrentClass { } The compiler complains that libtorrent::fingerprint a already defined in another class, because it has been inclused. So i move it to inside my class class TorrentClas...
In your .h file. Declare this: #ifndef CLASS_TORRENT_H #define CLASS_TORRENT_H #include "libtorrent.h" // I'm guessing this is the header file that declares the "fingerprint" class extern libtorrent::fingerprint a; class TorrentClass { public: TorrentClass(); // your class declaration goes here }; #endif In yo...
5,000,380
5,000,394
What's the use of C4711 "function selected for inline expansion" Visual C++ warning?
According to MSDN Visual C++ can emit C4711 warning: function X selected for inline expansion if the compiler decides to inline a function that was not marked inline. I don't see how this warning can be useful. Suppose I compile my code and see this warning. Now what? Why would I care?
It isn't on by default. You can turn it on if for some reason you'd like to know when functions are inlined. This can be relevant if, say, code size is at a severe premium, or you were expecting to jump into the function from outside the module, or you need the assembly to look a certain way. It can help track down cod...
5,000,665
5,000,984
Bilateral filtering with color
I understand generally the concepts behind bilateral filtering when using only grayscale images. I've read this website on bilateral filtering and the paper it discusses. My main problem is this: how can you determine the similarity of colors? Is the similarity of two RGB values the sum/product/some other operation of...
I checked out your link, and the answer is in there. It talks about first converting to the CIE-lab color space. Then you calculate the Euclidean distance between points, i.e. distance = sqrt(L*L + a*a + b*b) Here is a site that has several conversion formulae, for XYZ, RGB and LAB color spaces.
5,000,749
5,000,904
Avoiding double inclusion: Preprocessor directive vs. makefiles
I'm working on moving from frankenstein and one-file thousands-of-lines programs to well structured and organized, multi-file programs. Right now what seems to be natural (naively) is to make a love-triangle of header inclusions for three of my files: file_1 includes file_2, file_4 file_2 includes file_3, file_4 file_...
Preprocessor directives and headers containing declaration and shared structures etc is the way to go. Makefiles just helps to compile sources and to link object files to external libraries to form the final binary, it won't help to resolve the multiple-inclusion issue. In a nutshell, declare the following in a header ...
5,001,156
5,001,185
writing integer input to vector container in C++
likewise we do in array for (.....) cin>>a[i]; how we can do this using vectors. i declared a vector of integers vector<int> v; now i need to take inputs from console and add append those in vector.i am using vector because i donot know the limit.
To insert integer to a vector from console and print everything out: int input; vector<int> v; while(cin >> input){ v.push_back(input); } for(int i = 0; i<v.size(); i++){ cout<< v[i] <<endl; } And vector also provides you to print out the max size with: cout << v.max_size()<<endl;
5,001,184
5,001,967
Exe build by Code blocks is almost 57 times larger than the same code build by Visual studio
This code: #include <iostream> using namespace std; int main() { cout << "Hello world!\n"; return 0; } when comiled give size 457KB in Code::Blocks with GCC 4.4.1 and only 8KB (eight) in VS2010. Both compilers optimized for size. Anyone knows why such a difference?
You are right, the executable by gcc is obviously larger, in your case 57 times larger than that built by vc++. The main reason is the one made with GCC won't require any external dependencies to run while the one made with VS2010 would need at least its runtime files to be present on the system. For instance...
5,001,240
5,001,270
Template typedef of a template
Possible Duplicate: C++ template typedef I am trying to derive a template type of another template by pre-specializing of another template: template<unsigned a, unsigned b, unsigned c> struct test { enum { TEST_X = a, TEST_Y = b, TEST_Z = c, }; }; template<unsigned c> typedef tes...
This syntax isn't allowed by C++03. The nearest work-around is: template<unsigned c> struct test01 { typedef test<0, 1, c> type; }; typedef test01<2>::type my_type; In C++0x, we can do this: template<unsigned c> using test01 = test<0, 1, c>;
5,001,566
5,001,678
On Win32, can I disable painting of a window for a period of time?
Is there a function that will freeze window repainting for some time, while I do changes to the layout of my dialog?
If you find that you actually need to do this, you should send the window a WM_SETREDRAW message with the wParam set to FALSE. This indicates that the window should not be redrawn after its contents are changed. When you want to re-enable drawing, send another WM_SETREDRAW message, this time with the wParam set to TRUE...
5,001,903
5,001,928
tab marking in visual studio
I pressed in visual studio 2005 ctro+w, and then every tab in my code become: -> -> -> -> How do I get rid of these strange symbols?
Have you tried pressing ctrl+w again? In VS2008, the option is Edit -> Advanced -> View Whitespace. Not sure if it's the same in 2005.
5,001,984
5,002,021
Is it possible to name a CWinThread thread?
I have a C++ application (VS2008), and I start threads like this: CWinThread *myThread= AfxBeginThread(myOp,0); Now all I wan to do is name this thread, so I can identify it while debugging. It sounds like a simple task, but I could not find the way to do it. Is this possible, and if so, how?
This can be done relatively easily as documented on MSDN: How to set a Thread Name in Native Code. Essentially you send the debugger a magic exception containing the name and the thread ID, and the debugger then keeps track of and displays the name you sent it. The sample code from the MSDN article is included below: /...
5,001,993
5,002,105
checking user input for right value in C++
I have a requirment that accepts values from user input. It can be integers or strings. User input is accepted as below. string strArg; cout << "Enter price value " << endl; std::getline(std::cin, strArg); int input; std::stringstream(strArg) >> input; Question is how do i check user has entered integer, rather than ...
Something like this ought to do: #include <iostream> #include <sstream> #include <string> int main(void) { std::cout << "input:" << std::endl; std::string input; std::getline(std::cin, input); std::istringstream str(input); int iv = 0; // this checks that we've read in an int and we've consumed the entir...
5,002,046
5,002,256
Atomicity in C++ : Myth or Reality
I have been reading an article about Lockless Programming in MSDN. It says : On all modern processors, you can assume that reads and writes of naturally aligned native types are atomic. As long as the memory bus is at least as wide as the type being read or written, the CPU reads and writes these types in ...
This recommendation is architecture-specific. It is true for x86 & x86_64 (in a low-level programming). You should also check that compiler don't reorder your code. You can use "compiler memory barrier" for that. Low-level atomic read and writes for x86 is described in Intel Reference manuals "The Intel® 64 and IA-32 A...
5,002,055
5,002,201
Is the pointer guaranteed to preserve its value after `delete` in C++?
Inspired by this question. Suppose in C++ code I have a valid pointer and properly delete it. According to C++ standard, the pointer will become invalid (3.7.3.2/4 - the deallocation function will render invalid all pointers referring to all parts of deallocated storage). At least in most implementations it preserves t...
No, it's not guaranteed and an implementation may legitimately assign zero to an lvalue operand to delete. Bjarne Stroustrup had hoped that implementations would choose to do this, but not many do. http://www.stroustrup.com/bs_faq2.html#delete-zero
5,002,172
5,003,402
please provide the location of the "\msdev\include " directory. to download
I installed EDG compiler in Windows i.e in "win32". After installation I am trying to run this simple code: using namespace std; int main() { cout<<"OM"; return 0; } I am getting errors like unidentified cout, etc Actually I didn't give path dev libraries : there in read me file it is to give. ...
As far as I see from their page, EDG do not provide a full compiler, but only a front-end; it does not include neither an optimizer/code generator neither a standard library. You simply cannot use just EDG to produce an executable. You can find several free implementations of the C++ standard library (e.g. libstdc++ fr...
5,002,269
5,002,321
How to delete pointer only once?
enum Reaction{single,chain}; class X { X* parent_; X* left_; X* right_; Reaction* reaction_;//this pointer points from every obj to the same place, cannot be static }; The Q is: how to design destructor in order to delete reaction_ only once?
Three immediate ideas: 1) Must reaction_ be owned by an instance of class X? Can't it be owned by an external entity, so that no X::~X will ever need to delete it? 2) Use boost::shared_ptr 3) Implement your own reference counting using a static int. Remember locking if you're multithreaded.
5,002,343
5,002,380
Strange preprocessing
Something strange happens. I have in my code in a local function #ifdef abc . . . #endif when I write on the top of the file #define abc it acts as if it isn't defined. only when I define #define abc in the local function itself it reads the code in the ifdef. This is strange because I thought that the compiler ...
Probably you had the #define before #include "stdafx.h". This is ignored.
5,002,436
5,002,468
Comparison of custom objects and operator overloading in C++
Read this question about how to compare custom objects in C++. I did not understand the operator overloading used here. What is the operator being overloaded here? Is it ()? What is the use of overloading that? struct MyStruct { int key; std::string stringValue; MyStruct(int k, const std::string& s) : key(...
The point is to use a less_than_key object as a function: less_than_key f; bool result = f(key1, key2); Object that can be called like functions (including garden variety functions) are sometimes called functors (warning: this is not the meaning of functor in mathematics), or function objects, or sometimes functoids. ...
5,002,613
5,002,703
When is const_cast used in C++
Possible Duplicate: Correct usage(s) of const_cast<> What is the use of having a const parameter in the function argument and then using const_cast within the function?
I've only used const_cast on cases where I have to pass a const parameter to unmodifiable legacy code known to not modify the parameter, i.e. it is in practice const but the signature of the API/function call does not contain the const keyword.