question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
2,480,743 | 2,480,787 | Creating array with constant | I was working on a program in Netbeans on Linux using a gcc compiler when, upon switching to Visual C++ on Windows 7, the code failed to compile as Visual C++ says it expected constant expression on several lines. On Netbeans, I simply did something similar to char name[fullName.size()];, while on Visual C++, I tried, among other things,
const int position = fullName.size();
char Name[position];
How can I create a constant to use for the array?
Note: I know about this question, but is there any way I can get this working without using vectors, since that would require a re-write of many parts of the program?
| In VC++ you can't do runtime declarations of stack array sizes, but you can do stack allocation via _alloca
so this:
const int position = fullName.size();
char Name[position];
becomes this:
const int position = fullName.size();
char * Name = (char*)_alloca(position * sizeof(char));
It's not quite the same thing, but it's as close as you are going to get in VC++.
|
2,480,894 | 2,484,149 | MFC/WIN32: mouse hover highlight in listctrl | The ListView control of Windows Explorer gives a highlight to whatever item is under the mouse, without affecting the current selection. This helps enormously with relating what item a given tooltip applies to within a listview - especially in report mode.
However, I am currently unable to find any APIs that would give my MFC application's CListCtrl that same behavior. Extended styles only have LVS_EX_TRACKSELECT, which actually alters the current selection (yuck!).
Does anyone know how to provide a standard CListCtrl (or whatever that actually sits on top of) the mouse-hot-tracking capability?
I found some articles on how to provide per cell and per row tooltip text, but its hard to tell what the tooltips relate to without something highlighting...
| You can set the explorer theme to your list control. That way it will get a nicer look and you will also get the highlighting you want:
SetWindowTheme(hListControl, L"Explorer", NULL);
|
2,481,004 | 2,481,007 | Why aren't EXE's in binary? | Why is it that if you open up an EXE in a hex editor, you will see all sorts of things. If computers only understand binary then shouldn't there only be 2 possible symbols seen in the file? Thanks
| The hexadecimal values are interpreted binary values in memory. The software only make it a bit more readable to human beings.
0000 = 0
0001 = 1
0010 = 2
0011 = 3
0100 = 4
0101 = 5
0110 = 6
0111 = 7
1000 = 8
1001 = 9
1010 = 10 A
1011 = 11 B
1100 = 12 C
1101 = 13 D
1110 = 14 E
1111 = 15 F
|
2,481,142 | 2,481,163 | pointer to member function question | I'm trying to replicate a template I've used before with a member function, and it isn't going very well. The basic form of the function is
template<class T>
T Convert( HRESULT (*Foo)(T*))
{
T temp;
Foo(&temp); //Throw if HRESULT is a failure
return temp;
}
HRESULT Converter(UINT* val)
{
*val = 1;
return S_OK;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::cout << Convert<UINT>(Converter) << std::endl;
return 0;
}
For the life of me, I can't get this to work with a member variable. I've read up on their syntax, and I can't seem to figure out how to make it work with templates.
The class would be something similar to
class TestClass
{
HRESULT Converter(UINT* val)
{
*val = 1;
return S_OK;
}
}
| TestClass is stateless. So why do you want to pass a non-static member function? If in the real code you need access to non-static members, you also need to pass the object along
template<class T, class C>
T Convert( HRESULT (C::*Foo)(T*), C c)
{
T temp;
(c.*Foo)(&temp); //Throw if HRESULT is a failure
return temp;
}
You can then call it like the following, assuming the member function is made public
TestClass c;
Convert(&TestClass::Converter, c);
If the class is heavy-weight or if the function changes its object during execution, you may decide to pass the object to Convert by reference.
|
2,481,320 | 2,481,337 | What is the Best way to create a program which works only in the predefined trial period(evaluation period)? | I need to create a simple application that doesn't work after 30 days.
How can I do that ?
Is there a way to use Trial program after 30 days ?
| There is always a way to use a trial program after 30 days.
|
2,481,367 | 2,481,376 | How could one emulate namespace in C? | In C++ one might use namespace to keep independent groups working in the same code base from inadvertently creating functions with the same name and thus creating a conflict. My question is, before the idea of namespace comes out, how might one emulate namespace in C.
| By naming things differently, e.g.:
void namespace_group_function();
gtk+ is a prime example for this conventional style:
GtkWidget* gtk_window_new(GtkWindowType type);
|
2,481,535 | 2,481,547 | How to return a string literal from a function | I am always confused about return a string literal or a string from a function. I was told that there might be memory leak because you don't know when the memory will be deleted?
For example, in the code below, how to implement foo() so as to make the output of the code is "Hello World"?
void foo ( ) // you can add parameters here.
{
}
int main ()
{
char *c;
foo ( );
printf ("%s",c);
return 0;
}
Also, if the return type of foo() is not void, but you can return char*, what should it be?
| I'm assuming we cannot modify main. To get your program working without a leak, you need something to have static storage:
void foo(char*& pC) // reference
{
static char theString[] = "thingadongdong";
pC = theString;
}
But really, this isn't very conventional C++ code. You'd be using std::string and std::cout, so you don't have to worry about memory:
std::string foo(void)
{
return "better thingadongdong";
}
int main(void)
{
// memory management is done
std::cout << foo() << std::endl;
}
If you're wondering if something needs to be manually deallocated, it's being done wrong.
|
2,481,632 | 2,508,356 | Why implement DB connection pointer object as a reference counting pointer? (C++) | At our company one of the core C++ classes (Database connection pointer) is implemented as a reference counting pointer. To be clear, the objects are NOT DB connections themselves, but pointers to a DB connection object.
The library is very old, and nobody who designed is around anymore.
So far, nether I, nor any C++ experts in the company that I asked have come up with a good reason for why this particular design was chosen. Any ideas?
It is introducing some problems (partially due to awful reference pointer implementation used), and I'm trying to understand if this design actually has some deep underlying reasons?
The usage pattern these days seems to be that the DB connection pointer object is returned by a DB connection manager class, and it's somewhat unclear whether DB connection pointers were designed to be able to be used independently of DB connection manager.
| Probably it's a mistake. Without looking at the code it's impossible to know for sure, but the quality of the reference-counted pointer implementation is suggestive. Poor design, especially around resource management, is not unheard of in the C++ community</bitter sarcasm>.
With that said, reference-counted pointers are useful when you have objects of indeterminate lifetime which are very expensive to create, or whose state needs to be shared among several users. Depending on the underlying architecture, database connections could fit this definition: if each database connection needs to authenticate over the global internet, say, it could easily be worth your trouble to save a single connection and reuse it, rather than making new connections and disposing of them as you go.
But if I've understood you correctly, you don't have a single database connection object with a collection of refcounted pointers pointing to it. Rather, you have a database connection object, a collection of ordinary pointers to it, and a collection of refcounted pointers to those pointers. This is insanity, and almost certainly the result of confused thinking by the original developers. The alternative is that it was an act of deliberate evil, e.g. to ensure job security. If so they must have failed, as none of the perpetrators still work for your company.
|
2,481,654 | 2,481,668 | memset for initialization in C++ | memset is sometimes used to initialize data in a constructor like the example below. Does it work in general ? Is it a good idea in general?
class A {
public:
A();
private:
int a;
float f;
char str[35];
long *lp;
};
A::A()
{
memset(this, 0, sizeof(*this));
}
| Don't use memset. It's a holdover from C and won't work on non-PODs. Specifically, using it on a derived class that contains any virtual functions -- or any class containing a non-builtin -- will result in disaster.
C++ provides a specific syntax for initialization:
class A {
public:
A();
private:
int a;
float f;
char str[35];
long *lp;
};
A::A()
: a(0), f(0), str(), lp(NULL)
{
}
To be honest, I'm not sure, but memset might also be a bad idea on floating-points since their format is unspecified.
|
2,481,783 | 2,481,791 | What's the difference of pData1 and pData2, which are build as follows | What's the difference of pData1 and pData2, which are build as follows:
pData1 = (int*) calloc (i,sizeof(int));
int * pData2 = (int*) calloc (i,sizeof(int));
| Without any more information, it would appear the only difference is that pData2 is local to the allocation since it is declared as an int *. pData1 is not declared so it would have to have a larger (global?) scope and be defined elsewhere.
|
2,481,787 | 2,481,836 | Convert float to LPCWSTR/LPWSTR | [win 32 C++]
I don't know how to convert float to LPCWSTR/LPWSTR or LPCWSTR <-> LPWSTR
Thanks a lot
| #include <sstream>
...
float f = 45.56;
wstringstream wss;
wss << f;
// wss.str().c_str() returns LPCWSTR
cout << wss.str() << endl;
...
|
2,481,886 | 2,481,893 | Read/Write protected memory? | I'm trying to learn C++ currently, but I'm having issues with the code below.
class Vector2
{
public:
double X;
double Y;
Vector2(double X, double Y)
{
this->X = X;
this->Y = Y;
};
SDL_Rect * getSdlOffset()
{
SDL_Rect * offset = new SDL_Rect();
offset->x = this->X;
offset->y = this->Y;
return offset;
};
};
Visual studio throws throw the following error when calling getSdlOffset()
An unhandled exception of type
'System.AccessViolationException'
occurred in crossEchoTest.exe
Additional information: Attempted to
read or write protected memory. This
is often an indication that other
memory is corrupt.
I've got a C#/java background, and I'm lost... Any help would be much appreciated.
| You never initialized X or Y... what do you those values might be? More than likely they are point to 00000X00(I am rusty this may not be the right address, but you are pointed to memory outside of your programs allocated space... thus the "GPF" I was C/C++ "convert" to Java(over 11 years ago) so I can appreciate your ideas of how a pointer might behave--I can assure you that pointers are the most difficult part of C/C++ to understand, so you are on the right track in your learning. Just keep in mind that unlike Java/C#, C/C++ do not keep you from hurting yourself or the OS memory space/memory space of other programs. I alway remember what a teacher once told me when I was learning C--"With C you get a Kevlar boot and a gun, it is up to you whether or not you put the boot on before you shoot yourself in the foot, because you will shoot yourself at some point..." Good luck to you on learning C++, just hang in there and don't get discouraged.
WM
|
2,481,933 | 2,481,985 | Debugging strategy to find the cause of bad_alloc | I have a fairly serious bug in my program - occasional calls to new() throw a bad_alloc.
From the documentation I can find on bad_alloc, it seems to be thrown for these reasons:
When the computer runs out of memory (which definitely isn't happening, I have 4GB of RAM, program throws bad_alloc when using less than 5MB (checked in taskmanager) with nothing serious running in the background).
If the memory becomes too fragmented to allocate new blocks (which, again, is unlikely - the largest sized block I ever allocate would be about 1KB, and that doesn't get done more than 100 times before the crash occurs).
Based on these descriptions, I don't really have anywhere in which a bad_alloc could be thrown.
However, the application I am running runs more than one thread, which could possibly be contributing to the problem. By testing all of the objects on a single thread, everything seems to be working smoothly. The only other thing that I can think of that is going on here could be some kind of race-condition caused by calling new() in more than one place at the same time, but I've tried adding mutexes to prevent that behaviour to no effect.
Because the program is several hundred lines and I have no idea where the problem actually lies, I'm not sure of what, if any, code snippets to post. Instead, I was wondering if there were any tools that will help me test for this kind of thing, or if there are any general strategies that can help me with this problem.
I'm using Microsoft Visual Studio 2008, with Poco for threading.
| Another possible problem is that, while you mention that the program is using less than 5MB, you don't mention how much space it's trying to allocate. You could have some race condition that's corrupting the value that you use to determine the allocation size, and it could be trying to allocate 37TB or somesuch nonsense.
Not particularly likely, I suppose, but worth checking.
|
2,481,957 | 2,481,981 | How to find all the file handles by a process programmatically? | I have a process "x" which uses "system" C function to start ntpd daemon. I observed that ntpd are passed the open file descriptors of "x". ntpd holds on to the file descriptors even after original file is deleted. for ex: Some log files used by "x" are rotated out after sometime, but "ntpd" has file handle opened for these deleted files. Will it cause any problem?
Alternatively I thought of setting "FD_CLOEXEC" flag for all the file descriptors before calling "system" function. But as we are running as an extension library to third process "x"( "x" loads our library based on some condition), there is no easy way to know about all the file descriptors process has opened. One way is to read /proc//fd and set "FD_CLOEXEC" for each file handle and reset it back after "system" function returns. I'm using Linux 2.6.16. Is there any other easy way to find all the file handlers?
Thanks,
| Yes, it will cause a problem. The disk space used by the deleted files will not be released for reuse until the last open file descriptor is in fact closed.
Ideally, you would ensure that FD_CLOEXEC is set on all file descriptors; with POSIX 2008, you can do that when the file is opened with the O_CLOEXEC flag, even. But if you are part of another process and not in charge of its code, then it is not at all easy. Your choices are brute force and ignorance. You can cycle through all the descriptors you think might be open and close them - ignoring errors from descriptors that are already closed. That's brute force. Or you can ignore the files that are open, and hope that the system doesn't jam too badly. Maybe you can limit your search by checking how many files you can have open at once.
|
2,481,998 | 2,482,077 | How do I include extremely long literals in C++ source? | I've got a bit of a problem. Essentially, I need to store a large list of whitelisted entries inside my program, and I'd like to include such a list directly -- I don't want to have to distribute other libraries and such, and I don't want to embed the strings into a Win32 resource, for a bunch of reasons I don't want to go into right now.
I simply included my big whitelist in my .cpp file, and was presented with this error:
1>ServicesWhitelist.cpp(2807): fatal error C1091: compiler limit: string exceeds 65535 bytes in length
The string itself is about twice this allowed limit by VC++. What's the best way to include such a large literal in a program?
EDIT:
I'm storing the string like this:
const std::wstring servicesWhitelist
(
L".NETFRAMEWORK|"
L"_IOMEGA_ACTIVE_DISK_SERVICE_|"
L"{6080A529-897E-4629-A488-ABA0C29B635E}|"
L"{834170A7-AF3B-4D34-A757-E05EB29EE96D}|"
L"{85CCB53B-23D8-4E73-B1B7-9DDB71827D9B}|"
L"{95808DC4-FA4A-4C74-92FE-5B863F82066B}|"
L"{A7447300-8075-4B0D-83F1-3D75C8EBC623}|"
L"{D31A0762-0CEB-444E-ACFF-B049A1F6FE91}|"
L"{E2B953A6-195A-44F9-9BA3-3D5F4E32BB55}|"
L"{EDA5F5D3-9E0F-4F4D-8A13-1D1CF469C9CC}|"
L"2WIREPCP|"
//About 3800 more lines
);
EDIT2
It's used at runtime in a way similar to this:
static const boost::wregex servicesWhitelistRegex(servicesWhitelist);
std::wstring service;
//code to populate service
if (!boost::regex_match(service, servicesWhitelistRegex))
//Do something to print service
| How about an array? (you would put the commas only after the legal limit for every element)
const std::wstring servicesWhitelist[] = {
L".NETFRAMEWORK|",
L"_IOMEGA_ACTIVE_DISK_SERVICE_|",
L"{6080A529-897E-4629-A488-ABA0C29B635E}|",
L"{834170A7-AF3B-4D34-A757-E05EB29EE96D}|",
L"{85CCB53B-23D8-4E73-B1B7-9DDB71827D9B}|",
L"{95808DC4-FA4A-4C74-92FE-5B863F82066B}|",
L"{A7447300-8075-4B0D-83F1-3D75C8EBC623}|",
L"{D31A0762-0CEB-444E-ACFF-B049A1F6FE91}|",
L"{E2B953A6-195A-44F9-9BA3-3D5F4E32BB55}|",
L"{EDA5F5D3-9E0F-4F4D-8A13-1D1CF469C9CC}|",
L"2WIREPCP|",
...
};
You could use the below statement to get the combined string.
accumulate(servicesWhitelist, servicesWhitelist+sizeof(servicesWhitelist)/sizeof(servicesWhitelist[0]), "")
|
2,482,221 | 2,482,252 | Obtaining C++ Code Coverage |
I'm on Linux.
My code is written in C++.
My program is non-interactive; it runs as "./prog input-file", processes the file, and exits.
I have various unit tests "input-file0, input-file1, input-file2, ..."
For designing new unit tests, I want to know what lines of code existing tests do not cover.
Question: Given that I control how "prog" is compiled/run; how can I get list of the lines of code that "./prog input-file" does not hit?
Thanks!
EDIT: I'm currently using g++; but perfeclty happy to switch to LLVM if it makes this possible.
| gcc comes with a code coverage testing tool (gcov):
http://gcc.gnu.org/onlinedocs/gcc/Gcov.html
|
2,482,257 | 2,482,395 | Need recommendation for object serialization library in c++ | I am looking for recommendation for object serialization/deserialization library in c++? Which one are the most advanced and open-sourced?
Can it handle
Any class that users defined?
Object hierarchy (parent and child classes)?
A Tree of objects? Class A has an attribute of Class B which has an attribute of Class C?
STL containers? Class A has a vector of Class B?
A cyclic of objects? Class A has a pointer pointing to B which has a pointer to A?
I find boost serialization library. I am not sure what is its limitation from http://www.boost.org/doc/libs/1_42_0/libs/serialization/doc/tutorial.html
| It really depends what you're looking for. If you're looking for super-fast speed and rapid development within a library, Boost is awesome. If you're looking for super-fast speed, a little more customizability and cross-library binary compatibility, then Qt is a great solution (not saying that Boost can't be made to do this, too). If you're looking for crazy interoperability, then look for a text-based serialization system like JSON (jsoncpp), YAML (yamlcpp) or XML (way too many), each of which have about 8 billion independent libraries.
|
2,482,348 | 2,482,365 | Run C or C++ file as a script | So this is probably a long shot, but is there any way to run a C or C++ file as a script? I tried:
#!/usr/bin/gcc main.c -o main; ./main
int main(){ return 0; }
But it says:
./main.c:1:2: error: invalid preprocessing directive #!
| For C, you may have a look at tcc, the Tiny C Compiler. Running C code as a script is one of its possible uses.
|
2,482,435 | 2,482,443 | How to send message from one dialog to another? | I was given a task.
First dialog based application has 4
buttons (up, down, left, right).
Second dialog based application has
two controls (e.g. text area, button).
When on the first dialog I click
"left" button - controls on the second
dialog must move to the left.
But unfortunately I don't know Win32 API at all.
How can I implement it? What kind of Win32 API mechanism should I be using?
Thanks.
| If you got handles (HWND) to the controls on the other dialog then you can use the Win32 MoveWindow api call to move them.
When reading the api documentation it might be useful to remember that everything (buttons, list boxes, combo boxes etc) is a window...
|
2,482,526 | 2,482,612 | Cleaning up a dynamic array of Objects in C++ | I'm a bit confused about handling an array of objects in C++, as I can't seem to find information about how they are passed around (reference or value) and how they are stored in an array.
I would expect an array of objects to be an array of pointers to that object type, but I haven't found this written anywhere. Would they be pointers, or would the objects themselves be laid out in memory in an array?
In the example below, a custom class myClass holds a string (would this make it of variable size, or does the string object hold a pointer to a string and therefore take up a consistent amount of space. I try to create a dynamic array of myClass objects within a myContainer. In the myContainer.addObject() method I attempt to make a bigger array, copy all the objects into it along with a new object, then delete the old one. I'm not at all confident that I'm cleaning up my memory properly with my destructors - what improvements could I make in this area?
class myClass
{
private:
string myName;
unsigned short myAmount;
public:
myClass(string name, unsigned short amount)
{
myName = name;
myAmount = amount;
}
//Do I need a destructor here? I don't think so because I don't do any
// dynamic memory allocation within this class
};
class myContainer
{
int numObjects;
myClass * myObjects;
public:
myContainer()
{
numObjects = 0;
}
~myContainer()
{
//Is this sufficient?
//Or do I need to iterate through myObjects and delete each
// individually?
delete [] myObjects;
}
void addObject(string name, unsigned short amount)
{
myClass newObject = new myClass(name, amount);
myClass * tempObjects;
tempObjects = new myClass[numObjects+1];
for (int i=0; i<numObjects; i++)
tempObjects[i] = myObjects[i]);
tempObjects[numObjects] = newObject;
numObjects++;
delete newObject;
//Will this delete all my objects? I think it won't.
//I'm just trying to delete the old array, and have the new array hold
// all the objects plus the new object.
delete [] myObjects;
myObjects = tempObjects;
}
};
| An array in C++ is an array of objects laid out in memory.
So for example in:
struct pair {
int x; int y;
};
...
pair array[10];
Each item in the array is going to be with a size of two ints.
If you want an array of pointers you can simply declare one:
pair* array_of_pointers[10];
The string objects have pointers to the variable size part of the string. So they're safe.
In fact they're the important lesson here. Same way you use the string class to avoid excessive memory handling you can use the vector class to avoid all the troubles of handling a dynamic array.
For the case you're doing this as an exercise. Here are a few problems:
newObject needs to be allocated locally, without new. This will make the code correct (as newObject is not a pointer and new returns a pointer) and will also save you the trouble of explicitly handling memory. (On a more advanced note, this makes the code exception safe in one more location)
myObject is never initialized. And you don't use initialization lists in the constructor. The constructor should look like this:
myContainer() : numObjects(0), myObjects(NULL)
{
}
The destructors in the code are exactly as they should be.
|
2,482,564 | 2,482,604 | C++ Win32 Unhandled Exception Handler | currently I used SetUnhandledExceptionFilter() to provide callback to get information when an unhandled exception was occurred, that callback will provides me with EXCEPTION_RECORD which provides ExceptionAddress.
[1]what is actually ExceptionAddress is? does it the address of function / code that gives exception, or the memory address that some function tried to access?
[2]is there any better mechanism that could give me better information when unhandled exception occured? (I can't use debug mode or add any code that affect runtime performance, since crash is rare and only on release build when code run as fast as possible)
[3]is there any way for me to get several callstack address when unhandled exception occured.
[4]suppose ExceptionAddress has address A, and I have DLL X loaded and executed at base address A-x, and some other DLL Y at A+y, is it good to assume that crash was PROBABLY caused by code on DLL X?
| (1) The ExceptionAddress is the address of the code that caused the exception. In case of an access violation error (0xC0000005) one of the additional arguments of the exception record holds the address from which a read or a write was attempted and another argument tells if it was a read or a write. This is documented in the link you provide in the question.
(2) no. additionally, adding debug information to a release build doesn't affect performance. You can verify this and see for yourself.
(3) dbghelp.dll provides a complete library to investigate crashes. among athers there is StackWalk64 which allows you to get the complete stack of the crash.
(4) calling GetModuleHandleEx with the ExceptionAddress as an argument will get you the handle of the dll where the offending code resides. As to the question of which DLL CAUSED the crash, this depends on your definition of "CAUSED". A crash which occur in one dll can be the result of a bug in a completely different and unrelated dll.
|
2,482,716 | 2,482,746 | Function in c++ for finding if a word is prefix | Let say i have some words AB, AAB, AA.
AB is not a prefix to AAB but AA is a prefix to AAB because if i just add B at the end of AA it will become AAB, which is not possible with AB.
So, is there any function in c++ (STL) so that i can determine of two words if one is prefix to the another ?
Thanks.
| template<class C, class T, class A>
bool starts_with(std::basic_string<C,T,A> const& haystack,
std::basic_string<C,T,A> const& needle)
{
return needle.length() <= haystack.length() &&
std::equal(needle.begin(), needle.end(), haystack.begin());
}
Note that the length check is not premature optimization, it is required to meet std::equal's precondition.
|
2,482,890 | 2,482,908 | How to create static method that evaluates local static variable once? | I have a class with static method which has a local static variable. I want that variable to be computed/evaluated once (the 1st time I call the function) and for any subsequent invocation, it is not evaluated anymore. How to do that? Here's my class:
template<
typename T1 = int, unsigned N1 = 1,
typename T2 = int, unsigned N2 = 0,
typename T3 = int, unsigned N3 = 0,
typename T4 = int, unsigned N4 = 0,
typename T5 = int, unsigned N5 = 0,
typename T6 = int, unsigned N6 = 0,
typename T7 = int, unsigned N7 = 0,
typename T8 = int, unsigned N8 = 0,
typename T9 = int, unsigned N9 = 0,
typename T10 = int, unsigned N10 = 0,
typename T11 = int, unsigned N11 = 0,
typename T12 = int, unsigned N12 = 0,
typename T13 = int, unsigned N13 = 0,
typename T14 = int, unsigned N14 = 0,
typename T15 = int, unsigned N15 = 0,
typename T16 = int, unsigned N16 = 0>
struct GroupAlloc
{
static const uint32_t sizeClass;
static uint32_t getSize()
{
static uint32_t totalSize = 0;
totalSize += sizeof(T1)*N1;
totalSize += sizeof(T2)*N2;
totalSize += sizeof(T3)*N3;
totalSize += sizeof(T4)*N4;
totalSize += sizeof(T5)*N5;
totalSize += sizeof(T6)*N6;
totalSize += sizeof(T7)*N7;
totalSize += sizeof(T8)*N8;
totalSize += sizeof(T9)*N9;
totalSize += sizeof(T10)*N10;
totalSize += sizeof(T11)*N11;
totalSize += sizeof(T12)*N12;
totalSize += sizeof(T13)*N13;
totalSize += sizeof(T14)*N14;
totalSize += sizeof(T15)*N15;
totalSize += sizeof(T16)*N16;
totalSize = 8*((totalSize + 7)/8);
return totalSize;
}
};
EDIT:
Thanks all for your prompt help. +1 to everyone. I chose Tyler McHenry's answer because it does not need any comparison, purely static function evaluation. I will need this code for allocator so avoiding another "if" should be better. Thanks again!
EDIT:
gf's answer turned out to be the best one as it deals with assignment during compile-time and saves the program from thread-safe headache and explicit initialization. However, I respect the previous best answer. I will give credit here instead of changing the tick mark. Thanks everyone for helping!
| Make another static function that does the computation, and use that for the initialization of the variable, e.g.
static uint32_t computeSize()
{
uint32_t init_totalSize;
// Lots of code
return init_totalSize;
}
static uint32_t getSize()
{
static uint32_t totalSize = computeSize();
return totalSize;
}
Static variables are guaranteed to be initialized exactly once (the first time the function containing them is used).
Edit: But this is not thread-safe. This page explains why in great detail.
To make it thread-safe, it is not sufficient to wrap the initialization of totalSize (the call to computeSize) in a critical section, because static variable initialization is "compiler magic", and it can be that the variable to undergoes initialization at any time during the call to getSize before it is used, even before the function's first statement. What you need to do is prevent more than one thread from even calling getSize at the same time, which can be accomplished with yet another level of indirection, e.g.
static uint32_t computeSize()
{
uint32_t init_totalSize;
// Lots of code
return init_totalSize;
}
static uint32_t real_getSize()
{
static uint32_t totalSize = computeSize();
return totalSize;
}
static uint32_t getSize()
{
uint32_t totalSize;
/* --- Enter Critical Section (acquire lock) -- */
totalSize = real_getSize();
/* --- Exit Critical Section (release lock) -- */
return totalSize;
}
This prevents two threads from even entering the function that contains the static variable at the same time, and ensure that its initialization will occur within a critical section.
|
2,483,426 | 2,483,521 | Debugging metaprograms | Is there any way to check step by step what's going on in let's say template? I mean how it is instantiated step by step and so on?
In book I've mentioned here ,
I found (2 minutes ago) quite interesting example of how binary could be implemented as a metafunction.
template <unsigned long N>
struct binary
{
static unsigned const value
= binary<N/10>::value << 1 // prepend higher bits
| N%10; // to lowest bit
};
template <> // specialization
struct binary<0> // terminates recursion
{
static unsigned const value = 0;
};
and I think it could be quite useful to be able to see step by step what's been done during the instantiation of this template.
Thanks for your replies.
| The best i've seen this far was the research paper on Templight, but i am not aware of any publicized implementation.
You can help yourself much though by using descriptive static (i.e. compile time) assertions - see e.g. Boosts static assert or MPLs asserts. In some cases it can help to provoke a compile error (e.g. by using static asserts) to get a template instantiation trace from the compiler.
Also there is nothing preventing you from a runtime output of meta-function results for testing.
|
2,483,491 | 2,483,937 | C++ Implicit Conversion Operators | I'm trying to find a nice inheritance solution in C++.
I have a Rectangle class and a Square class. The Square class can't publicly inherit from Rectangle, because it cannot completely fulfill the rectangle's requirements. For example, a Rectangle can have it's width and height each set separately, and this of course is impossible with a Square.
So, my dilemma. Square obviously will share a lot of code with Rectangle; they are quite similar.
For examlpe, if I have a function like:
bool IsPointInRectangle(const Rectangle& rect);
it should work for a square too. In fact, I have a ton of such functions.
So in making my Square class, I figured I would use private inheritance with a publicly accessible Rectangle conversion operator. So my square class looks like:
class Square : private Rectangle
{
public:
operator const Rectangle&() const;
};
However, when I try to pass a Square to the IsPointInRectangle function, my compiler just complains that "Rectangle is an inaccessible base" in that context. I expect it to notice the Rectangle operator and use that instead.
Is what I'm trying to do even possible?
If this can't work I'm probably going to refactor part of Rectangle into MutableRectangle class.
Thanks.
| Well, I'm surprised. It seems privately inheriting a class A prevents you from using operator A outside the class.
You can solve your problem by making a member Rectangle for square and using it for the cast:
class Square {
Rectangle r;
public:
operator const Rectangle&() const {
return r;
}
};
This should compile and work. And I believe it won't give you that much more work to do if any.
|
2,483,577 | 2,483,603 | operator new and new operator, which can't be overloaded? | It seems both can be overloaded, but somebody said not.....
What's the case?
| It seems you are making the distinction between the handling of new-expressions and allocation functions. new-expressions call constructors in addition for class types and is responsible for looking up allocation functions (so it is built into the compiler) and calling them. You can't change that behavior. What you can change is the behavior of allocation functions. Their name is operator new and they are found and used by new-expressions to allocate memory.
See Plain new, new[], delete and delete[] in a nutshell.
|
2,483,648 | 2,483,666 | C++ new line not translating | First off, I'm a complete beginner at C++.
I'm coding something using an API, and would like to pass text containing new lines to it, and have it print out the new lines at the other end.
If I hardcode whatever I want it to print out, like so
printInApp("Hello\nWorld");
it does come out as separate lines in the other end, but if I retrieve the text from the app using a method that returns a const char then pass it straight to printInApp (which takes const char as argument), it comes out as a single line.
Why's this and how would I go about to fix it?
| It is the compiler that process escape codes in string literals, not the runtime methods. This is why you can for example have "char c = '\n';" since the compiler just compiles it as "char c = 10".
If you want to process escape codes in strings such as '\' and 'n' as separate characters (eg read as such from a file), you will need to write (or use an existing one) a string function which finds the escape codes and converts them to other values, eg converting a '\' followed by a 'n' into a newline (ascii value 10).
|
2,483,679 | 2,483,724 | When is "this" pointer initialized in C++? | Hi I have a question about this pointer, when an object is constructed, when it is initialized? Which means, when can I use it? The virtual table is constructed in the constructor, is the same with this pointer?
For example, I have a code like this. The output is 8. Does it mean that before the constructor is entered, this pointer is already initialized?
class A{
public:
A() { cout<<sizeof(*this);}
int i;
int *p;
};
int main() {
A a;
}
If it is true, what else would happen before the constructor is entered ?
If it is not true, when is the this pointer initialized ?
| The this pointer isn't a member of the object or class - it's an implicit parameter to the method that you call. As such it's passed in much like any other parameter - except that you don't directly ask for it.
In your example above, the constructor is a special method, which is in turn a special kind of function. When you construct the object, the compiler allocates memory for it (in this case on the stack, as a is a local variable in the main function. Then it automatically calls the constructor to initialise the object.
As part of calling the constructor, the implicit parameter this - a pointer to your object - is passed in as a parameter.
In a method with the following signature...
void MyMethod (const int* p) const;
there are actually two parameters, both pointers. There's the explicit parameter p and the implicit parameter this. The const at the end of the line specifies that this is a const pointer, much as the earlier one specifies that p is a const pointer. The need for that special syntax only exists because this is passed implicitly, so you can't specify const-ness in the normal way as with other parameters.
A "static" method doesn't have the implicit "this" parameter, and cannot directly access the object members either - there may not be a particular object associated with the call. It is basically a standard function rather than a method, except with access to private members (providing it can find an object to access).
As Steve Fallows points out, sizeof (this) is known at compile-time, because it is a pointer type and all pointers (*1) have the same sizeof value. The "8" you see implies you are compiling for a 64-bit platform. this is usable at this point - it points to valid memory, and all the members have completed their constructor calls. However, it isn't necessarily fully initialised - you are still in the constructor call after all.
EDIT
*1 - strictly, that may not be true - but the compiler knows what type of pointer it's dealing with here even though the value isn't known until runtime.
|
2,483,755 | 2,483,802 | How to programmatically gain root privileges? | I am writing some software (in C++, for Linux/Mac OSX) which runs as a non-privileged user but needs root privileges at some point (to create a new virtual device).
Running this program as root is not a option (mainly for security issues) and I need to know the identity (uid) of the "real" user.
Is there a way to mimic the "sudo" command behavior (ask for user password) to temporarily gain root privileges and perform the particular task ? If so, which functions would I use ?
Thank you very much for your help !
| Original answer
You might consider the setuid switch on the executable itself. Wikipedia has an article on it which even shows you the difference between geteuid() and getuid() quite effectively, the former being for finding out who you're "emulating" and the latter for who you "are". The sudo process, for example, geteuid should return 0 (root) and getuid your user's id, however, its sub-processes do truly run as root (you can verify this with sudo id -u -r).
I don't think there's a way to easily programmatically gain root access - after all, applying the principle of least privilege, why would you need to? Common practise is to run only limited parts of code with elevated privileges. A lot of daemons etc are also set up under modern systems to run as their own user with most of the privileges they need. It's only for very specific operations (mounting etc) that root privileges are truly needed.
2013 update
My original answer stands (although my 2013 self might make a better job of it than my 2010 one), but if you are designing an application that requires root access, you may want to consider exactly what sort of root access is needed and consider the use of POSIX Capabilities (man page). These are different to capability-based security as implemented in L4 et al. POSIX capabilities allow your application to be granted a subset of root's powers. For example CAP_SYS_MODULE will allow you to insert kernel modules, but give you no other root powers. This is in use in distributions e.g. Fedora has a feature to completely remove setuid binaries with indiscriminate root access.
This matters because as a programmer, your code is obviously perfect! But, the libraries on which you depend (sigh, if only you'd written them!) might have vulnerabilities in them. Using capabilities, you can limit the use of this exploit, and save yourself and your company from security-related scrutiny. This makes everyone happier.
|
2,483,978 | 2,484,279 | Best way to implement globally scoped data | I'd like to make program-wide data in a C++ program, without running into pesky LNK2005 errors when all the source files #includes this "global variable repository" file.
I have 2 ways to do it in C++, and I'm asking which way is better.
The easiest way to do it in C# is just public static members.
C#:
public static class DataContainer
{
public static Object data1 ;
public static Object data2 ;
}
In C++ you can do the same thing
C++ global data way#1:
class DataContainer
{
public:
static Object data1 ;
static Object data2 ;
} ;
Object DataContainer::data1 ;
Object DataContainer::data2 ;
However there's also extern
C++ global data way #2:
class DataContainer
{
public:
Object data1 ;
Object data2 ;
} ;
extern DataContainer * dataContainer ; // instantiate in .cpp file
In C++ which is better, or possibly another way which I haven't thought about?
The solution has to not cause LNK2005 "object already defined" errors.
| If you absolutely have to have some global objects then the simplest way is to just to declare them extern in a header file included anywhere that needs access to them and define them in a single source file.
Your way #1 uses a class with only static members which means that it is essentially doing the job of a namespace so why not just use a namespace?
Way #2 aggregates both objects in a single class but if there is no true interdependency between the two objects there is no particular benefit to this.
I'd recommend putting the objects in a namespace prevent pollution of the global namespace with potentially common identifiers like data1,
// File: globaldata.h
#ifndef GLOBALDATA_H
#define GLOBALDATA_H
#include "Object.h" // Definition of Object might be here
namespace GlobalData
{
extern Object data1;
extern Obejct data2;
}
#endif GLOBALDATA_H
.
// File: globaldata.cc
#include globaldata.h
namespace GlobalData
{
Object data1;
Object data2;
}
Then you can access them in other places like this.
#include "globaldata.h"
// Does something with global data
void f()
{
GlobalData::data1.doSomething();
}
|
2,484,058 | 2,484,061 | How default assignment operator works in struct? | Suppose I have a structure in C++ containing a name and a number, e.g.
struct person {
char name[20];
int ssn;
};
Suppose I declare two person variables:
person a;
person b;
where a.name = "George", a.ssn = 1, and b.name = "Fred" and b.ssn = 2.
Suppose later in the code
a = b;
printf("%s %d\n",a.name, a.ssn);
| The default assignment operator does a member-wise recursive assignment of each member.
|
2,484,265 | 2,495,032 | How do I get rid of LD_LIBRARY_PATH at run-time? | I am building a C++ application that uses Intel's IPP library. This library is installed by default in /opt and requires you to set LD_LIBRARY_PATH both for compiling and for running your software (if you choose the shared library linking, which I did). I already modified my configure.ac/Makefile.am so that I do not need to set that variable when compiling, but I still can't find the shared library at run-time; how do I do that?
I'm compiling with the -Wl, -R/path/to/libdir flag using g++
Update 1:
Actually my binary program has some IPP libraries correctly linked, but just one is not:
$ ldd myprogram
linux-vdso.so.1 => (0x00007fffa93ff000)
libippacem64t.so.6.0 => /opt/intel/ipp/6.0.2.076/em64t/sharedlib/libippacem64t.so.6.0 (0x00007f22c2fa3000)
libippsem64t.so.6.0 => /opt/intel/ipp/6.0.2.076/em64t/sharedlib/libippsem64t.so.6.0 (0x00007f22c2d20000)
libippcoreem64t.so.6.0 => /opt/intel/ipp/6.0.2.076/em64t/sharedlib/libippcoreem64t.so.6.0 (0x00007f22c2c14000)
[...]
libiomp5.so => not found
libiomp5.so => not found
libiomp5.so => not found
Of course the library is there:
$ locate libiomp5.so
/opt/intel/ipp/6.0.2.076/em64t/sharedlib/libiomp5.so
| As suggested by Richard Pennington, the missing library is not used directly by my application, but it is used by the shared libraries I use. Since I cannot recompile IPP, the solution to my problem is to add -liomp5 when compiling, using the -R option for the linker. This actually adds the rpath for libiomp5.so fixing the problem!
|
2,484,324 | 2,484,329 | C++ return double pointer from function.... what's wrong? | I can't seem to figure out what's wrong with my function.... I need to ask the user for a price and then return it as a double pointer, but I get tons and tons of errors:
double* getPrice()
{
double* price;
cout << "Enter Price of CD: " << endl;
cin >> &price;
return price;
}
| In order to use a pointer of any kind it needs to point to valid memory. Right now you have a pointer which is uninitialized and points to garbage. Try the following
double* price = new double();
Additionally you need to have cin pass to a double not a double**.
cin >> *price;
Note this will allocate new memory in your process which must be freed at a later time. Namely by the caller of getPrice. For example
double* p = getPrice();
...
delete p;
Ideally in this scenario you shouldn't be allocated a pointer at all because it introduces unnecessary memory management overhead. A much easier implementation would be the following
double getPrice() {
double price;
cout << "Enter Price of CD: " << endl;
cin >> price;
return price;
}
|
2,484,337 | 2,484,459 | Performance of std::pow - cache misses? | I've been trying to optimize a numeric program of mine, and have run into something of a mystery. I'm looping over code that performs thousands of floating point operations of which 1 call to pow - nevertheless, that call takes 5% of the time... That's not necessarily a critical issue, but it is odd, so I'd like to understand what's happening.
When I profiled for cache misses, VS.NET 2010RC's profiler reports that virtually all cache misses are occurring in std::pow... so... what's up with that? Is there a faster alternative? I tried powf, but that's only slightly faster; it's still responsible for an abnormal number of cache misses.
Why would a basic function like pow cause cache-misses?
Edit: this is not managed code. /Oi intrinsics are enabled, but the compiler may at its option ignore that. Replacing pow(x,y) by exp(y*log(x)) has similar performance - just now all the cache misses are in the log function.
| If you replace std::pow(var) with another function, like std::max(var, var), does it still take up 5%? Do you still get all the cache misses?
I'm guessing no on time and yes on cache misses. Calculating powers is slower than many other operations (which are you using?). Calling out to code that's not in the cache will cause a cache miss no matter which function it is.
|
2,484,355 | 2,484,393 | STL Vectors, pointers and classes | Let's say i have 2 classes:
class Class1
{
public:
std::vector<CustomClass3*> mVec;
public:
Class1();
~Class1()
{
//iterate over all the members of the vector and delete the objects
}
};
class InitializerClass2
{
private:
Class1 * mPtrToClass1;
public:
InitializerClass2();
void Initialize()
{
mPtrToClass1->mVec.push_back(new CustomClass3(bla bla parameters));
}
};
Will this work? Or the memory allocated in the InitializerClass2::Initialize() method might get corrupted after the method terminates?
Thanks!
| In short this will work fine.
The memory being allocated in Initialize is on the heap. This means that changes in the stack do not affect the contents of this memory.
|
2,484,389 | 2,484,878 | Is it ok to pass *this in the constructor in the following example | Class A
{
A(B& b) : mb(b)
{
// I will not access anything from B here
}
B& mb;
};
Class B
{
B(): a(*this)
{}
A a;
}
I run into such a situation may times, the contained object needs to use the containers functionality. Having a reference to the container object in the contained object seems to be the best way to do this. Of course, I could do this with a pointer, that way I could have a setter setB(B* b) {mb = b;} which I could call later after I am sure B is initialized but I would much prefer to do this with a reference which means I need to initialize it in the constructor, hence the problem.
| The appropriate quote from the standard is:
§3.8 [basic.life]/6
Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated or, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any lvalue which refers to the original object may be used but only in limited ways. Such an lvalue refers to allocated storage (3.7.3.2), and using the properties of the lvalue which do not depend on its value is well-defined. If an lvalue-to-rvalue conversion (4.1) is applied to such an lvalue, the program has undefined behavior; if the original object will be or was of a non-POD class type, the program has undefined behavior if:
— the lvalue is used to access a non-static data member or call a non-static member function of the object, or
— the lvalue is implicitly converted (4.10) to a reference to a base class type, or
— the lvalue is used as the operand of a static_cast(5.2.9) (except when the conversion is ultimately to char& or unsigned char&), or
— the lvalue is used as the operand of a dynamic_cast(5.2.7) or as the operand oftypeid.
|
2,484,511 | 3,580,205 | Can I use Visual Studio 2010's C++ compiler with Visual Studio 2008's C++ Runtime Library? | I have an application that needs to operate on Windows 2000. I'd also like to use Visual Studio 2010 (mainly because of the change in the definition of the auto keyword). However, I'm in a bit of a bind because I need the app to be able to operate on older OS's, namely:
Windows 2000
Windows XP RTM
Windows XP SP1
Visual Studio 2010's runtime library depends on the EncodePointer / DecodePointer API which was introduced in Windows XP SP2.
If using the alternate runtime library is possible, will this break code that relies on C++0x features added in VS2010, like std::regex?
| Suma's solution looked pretty promising, but it doesn't work: the __imp__*@4 symbols need to be pointers to functions, rather than the functions themselves. Unfortunately, I don't know how to make Visual C++ spit out a pointer with that kind of name generation... (well, __declspec(naked) combined with __stdcall does the trick, but then I don't know how to emit a pointer).
If using an assembler at build-time is OK, the solution is pretty trivial - assemble the following code with FASM and link against the produced object file, and presto - no EncodePointer/DecodePointer references in the exe:
use32
format ms coff
section ".data" data
public __imp__DecodePointer@4
__imp__DecodePointer@4 dd dummy
public __imp__EncodePointer@4
__imp__EncodePointer@4 dd dummy
section ".text" code
dummy:
mov eax, [esp+4]
retn 4
|
2,484,570 | 2,484,607 | Help understanding linux/tcp.h | I'm learning to use raw sockets, and im trying to prase out the tcp header data, but i can't seem to figure out what res1, ece, and cwr are. Through my networking book and google i know what the rest stand for, but can't seem to find anything on those three.
Below is the tcphdr struct in my includes area. Ive commented the parts a bit as i was figureing out what they stood for.
struct tcphdr {
__be16 source;
__be16 dest;
__be32 seq;
__be32 ack_seq;
\#if defined(__LITTLE_ENDIAN_BITFIELD)
__u16 res1:4,
doff:4,//tcp header length
fin:1,//final
syn:1,//synchronization
rst:1,//reset
psh:1,//push
ack:1,//ack
urg:1,// urge
ece:1,
cwr:1;
\#elif defined(__BIG_ENDIAN_BITFIELD)
__u16 doff:4,//tcp header length
res1:4,
cwr:1,
ece:1,
urg:1,//urge
ack:1,//ack
psh:1,//push
rst:1,//reset
syn:1,//synchronization
fin:1;//final
\#else
\#error "Adjust your <asm/byteorder.h> defines"
\#endif
__be16 window;
__sum16 check;
__be16 urg_ptr;
};
| See http://en.wikipedia.org/wiki/Transmission_Control_Protocol#TCP_segment_structure
res1 is called reserved there. The others have the same name.
CWR (1 bit) – Congestion Window Reduced (CWR)
ECE (1 bit) – ECN-Echo indicates
|
2,484,606 | 2,484,756 | c++ library for endian-aware reading of raw file stream metadata? | I've got raw data streams from image files, like:
vector<char> rawData(fileSize);
ifstream inFile("image.jpg");
inFile.read(&rawData[0]);
I want to parse the headers of different image formats for height and width. Is there a portable library that can can read ints, longs, shorts, etc. from the buffer/stream, converting for endianess as specified?
I'd like to be able to do something like: short x = rawData.readLeShort(offset); or long y = rawData.readBeLong(offset)
An even better option would be a lightweight & portable image metadata library (without the extra weight of an image manipulation library) that can work on raw image data. I've found that Exif libraries out there don't support png and gif.
| It's not that hard to do yourself. Here's how you can read a little endian 32 bit number:
unsigned char buffer[4];
inFile.read(buffer, sizeof(buffer));
unsigned int number = buffer[0] +
(buffer[1] << 8) +
(buffer[2] << 16) +
(buffer[3] << 24);
and to read a big endian 32 bit number:
unsigned char buffer[4];
inFile.read(buffer, sizeof(buffer));
unsigned int number = buffer[3] +
(buffer[2] << 8) +
(buffer[1] << 16) +
(buffer[0] << 24);
|
2,484,669 | 2,484,702 | Returning a dynamically created array from function | I'm trying to create a function that would dynamically allocate an array, sets the values of the elements, and returns the size of the array. The array variable is a pointer that is declared outside the function and passed as a parameter. Here is the code:
#include <cstdlib>
#include <iostream>
using namespace std;
int doArray(int *arr) {
int sz = 10;
arr = (int*) malloc(sizeof(int) * sz);
for (int i=0; i<sz; i++) {
arr[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
For some reason, the program terminates on the first iteration of the for loop in main()! Am I doing something wrong?
| You're passing in the array pointer by value; this means that when your doArray function returns, the value in arr in main is still NULL - the assignment inside doArray doesn't change it.
If you want to change the value of arr (which is an int *), you need to pass in either a pointer or a reference to it; hence, your function signature will contain either (int *&arr) or (int **arr). If you pass it in as a ** you'll also have to change the syntax inside the function from using arr to *arr (pointer-dereferencing), and you'll call it like so: doArray(&arr).
Also, in C++ you should really be using new int[sz] instead of malloc.
|
2,484,766 | 2,484,788 | When to put C++ function in header file | I've been looking at Boost and various other C++ libraries. The vast majority of Boost is implemented in header files.
My question is: under what conditions do you do a header-only implementation (like Boost) or also include a .cpp file?
| If you want to use a template in another translation unit (i.e. another source file), you should (almost always) define it in the header file. (There are exceptions, like the comments below point out, but IMHO this is a good rule of thumb.)
Same applies if you want to use an inline function from another translation unit.
Otherwise you should put the implementation into a separate .cpp file to minimize dependencies.
|
2,484,829 | 2,487,316 | How to redraw the picture while moving windows in openGL? | I have drawn a picture with openGL on my windows. Now whenever I hold the mouse button on the windows and move it, my picture always got distorted. I don't know what function in openGL that can help me redraw the picture while the windows is moved. Anybody could help?
I tried this but seems not work:
void myDisplay()
{
.....
}
void reshape(int x, int y)
{
glutPostRedisplay();
}
int main()
{
.....
glutDisplayFunc(myDisplay);
glutReshapeFunc(reshape);
}
| The first (and usually only) necessary step is to to quit using glut. glut is oriented primarily toward producing a static display, so it attempts to accumulate changes and then redraw only when the state has "stabilized" again, such as when you're done resizing the window. That made sense at one time, but mostly doesn't anymore.
Given that it's been around 10 years since glut was last updated, out of date design goals are hardly a surprise. That doesn't change the fact that it's carefully written to prevent what you want from happening. If you wanted to, you could probably rewrite it to fit your expectations better, but it'll almost certainly be quite a bit simpler to use something else that's designed to do what you want (or at least something closer to what you want).
|
2,484,959 | 2,485,010 | Can you force a crash if a write occurs to a given memory location with finer than page granularity? | I'm writing a program that for performance reasons uses shared memory (sockets and pipes as alternatives have been evaluated, and they are not fast enough for my task, generally speaking any IPC method that involves copies is too slow). In the shared memory region I am writing many structs of a fixed size. There is one program responsible for writing the structs into shared memory, and many clients that read from it. However, there is one member of each struct that clients need to write to (a reference count, which they will update atomically). All of the other members should be read only to the clients.
Because clients need to change that one member, they can't map the shared memory region as read only. But they shouldn't be tinkering with the other members either, and since these programs are written in C++, memory corruption is possible. Ideally, it should be as difficult as possible for one client to crash another. I'm only worried about buggy clients, not malicious ones, so imperfect solutions are allowed.
I can try to stop clients from overwriting by declaring the members in the header they use as const, but that won't prevent memory corruption (buffer overflows, bad casts, etc.) from overwriting. I can insert canaries, but then I have to constantly pay the cost of checking them.
Instead of storing the reference count member directly, I could store a pointer to the actual data in a separate mapped write only page, while keeping the structs in read only mapped pages. This will work, the OS will force my application to crash if I try to write to the pointed to data, but indirect storage can be undesirable when trying to write lock free algorithms, because needing to follow another level of indirection can change whether something can be done atomically.
Is there any way to mark smaller areas of memory such that writing them will cause your app to blow up? Some platforms have hardware watchpoints, and maybe I could activate one of those with inline assembly, but I'd be limited to only 4 at a time on 32-bit x86 and each one could only cover part of the struct because they're limited to 4 bytes. It'd also make my program painful to debug ;)
Edit: I found this rather eye popping paper, but unfortunately it requires using ECC memory and a modified Linux kernel.
| I don't think its possible to make a few bits read only like that at the OS level.
One thing that occurred to me just now is that you could put the reference counts in a different page like you suggested. If the structs are a common size, and are all in sequential memory locations you could use pointer arithmetic to locate a reference count from the structures pointer, rather than having a pointer within the structure. This might be better than having a pointer for your use case.
long *refCountersBase;//The start address of the ref counters page
MyStruct *structsBase;//The start address of your structures page
//get address to reference counter
long *getRefCounter(MyStruct *myStruct )
{
size_t n = myStruct - structsBase;
long *ref = refCountersBase + n;
return ref;
}
|
2,484,980 | 2,485,177 | Why is volatile not considered useful in multithreaded C or C++ programming? | As demonstrated in this answer I recently posted, I seem to be confused about the utility (or lack thereof) of volatile in multi-threaded programming contexts.
My understanding is this: any time a variable may be changed outside the flow of control of a piece of code accessing it, that variable should be declared to be volatile. Signal handlers, I/O registers, and variables modified by another thread all constitute such situations.
So, if you have a global int foo, and foo is read by one thread and set atomically by another thread (probably using an appropriate machine instruction), the reading thread sees this situation in the same way it sees a variable tweaked by a signal handler or modified by an external hardware condition and thus foo should be declared volatile (or, for multithreaded situations, accessed with memory-fenced load, which is probably a better a solution).
How and where am I wrong?
| The problem with volatile in a multithreaded context is that it doesn't provide all the guarantees we need. It does have a few properties we need, but not all of them, so we can't rely on volatile alone.
However, the primitives we'd have to use for the remaining properties also provide the ones that volatile does, so it is effectively unnecessary.
For thread-safe accesses to shared data, we need a guarantee that:
the read/write actually happens (that the compiler won't just store the value in a register instead and defer updating main memory until much later)
that no reordering takes place. Assume that we use a volatile variable as a flag to indicate whether or not some data is ready to be read. In our code, we simply set the flag after preparing the data, so all looks fine. But what if the instructions are reordered so the flag is set first?
volatile does guarantee the first point. It also guarantees that no reordering occurs between different volatile reads/writes. All volatile memory accesses will occur in the order in which they're specified. That is all we need for what volatile is intended for: manipulating I/O registers or memory-mapped hardware, but it doesn't help us in multithreaded code where the volatile object is often only used to synchronize access to non-volatile data. Those accesses can still be reordered relative to the volatile ones.
The solution to preventing reordering is to use a memory barrier, which indicates both to the compiler and the CPU that no memory access may be reordered across this point. Placing such barriers around our volatile variable access ensures that even non-volatile accesses won't be reordered across the volatile one, allowing us to write thread-safe code.
However, memory barriers also ensure that all pending reads/writes are executed when the barrier is reached, so it effectively gives us everything we need by itself, making volatile unnecessary. We can just remove the volatile qualifier entirely.
Since C++11, atomic variables (std::atomic<T>) give us all of the relevant guarantees.
|
2,485,030 | 2,485,040 | deleting HBITMAP causes an access violation at runtime | I have the following code to take a screenshot of a window, and get the colour of a specific pixel in it:
void ProcessScreenshot(HWND hwnd){
HDC WinDC;
HDC CopyDC;
HBITMAP hBitmap;
RECT rt;
GetClientRect (hwnd, &rt);
WinDC = GetDC (hwnd);
CopyDC = CreateCompatibleDC (WinDC);
//Create a bitmap compatible with the DC
hBitmap = CreateCompatibleBitmap (WinDC,
rt.right - rt.left, //width
rt.bottom - rt.top);//height
SelectObject (CopyDC, hBitmap);
BitBlt (CopyDC, //destination
0,0,
rt.right - rt.left, //width
rt.bottom - rt.top, //height
WinDC, //source
0, 0,
SRCCOPY);
COLORREF col = ::GetPixel(CopyDC,145,293);
// Do some stuff with the pixel colour....
delete hBitmap;
ReleaseDC(hwnd, WinDC);
ReleaseDC(hwnd, CopyDC);
}
the line 'delete hBitmap;' causes a runtime error: an access violation. I guess I can't just delete it like that?
Because bitmaps take up a lot of space, if I don't get rid of it I will end up with a huge memory leak. My question is: Does releasing the DC the HBITMAP is from deal with this, or does it stick around even after I have released the DC? If the later is the case, how do I correctly get rid of the HBITMAP?
| You must destroy GDI objects with DeleteObject, not delete. The latter is only used to free objects allocated using new.
|
2,485,057 | 2,485,109 | Pipe multiple files (gz) into C program | I've written a C program that works when I pipe data into my program using stdin like:
gunzip -c IN.gz|./a.out
If I want to run my program on a list of files I can do something like:
for i `cat list.txt`
do
gunzip -c $i |./a.out
done
But this will start my program 'number of files' times.
I'm interested in piping all the files into the same process run.
Like doing
for i `cat list.txt`
do
gunzip -c $i >>tmp
done
cat tmp |./a.out
How can I do this?
| There is no need for a shell loop:
gzip -cd $(<list.txt) | ./a.out
With the '-cd' option, gzip will uncompress a list of files to standard output (or you can use 'gunzip -c'). The $(<file) notation expands the contents of the named file as a list of arguments without launching a sub-process. It is equivalent to $(cat list.txt) otherwise.
However, if you feel you must use a loop, then simply pipe the output from the loop into a single instance of your program:
for i in `cat list.txt`
do
gunzip -c $i
done |
./a.out
If the contents of the loop are more complex (than simply gunzipping a single file), this might be necessary. You can also use '{ ... }' I/O redirection:
{
cat /etc/passwd /etc/group
for i in `cat list.txt`
do
gunzip -c $i
done
} |
./a.out
Or:
{
cat /etc/passwd /etc/group
for i in `cat list.txt`
do
gunzip -c $i
done; } |
./a.out
Note the semi-colon; it is necessary with braces. In this example, it is essentially the same as using a formal sub-shell with parentheses:
(
cat /etc/passwd /etc/group
for i in `cat list.txt`
do
gunzip -c $i
done
) |
./a.out
Or:
( cat /etc/passwd /etc/group
for i in `cat list.txt`
do
gunzip -c $i
done) |
./a.out
Note the absence of a semi-colon here; it is not needed. The shell is wonderfully devious on occasion. The braces I/O redirection can be useful when you need to group commands after the pipe symbol:
some_command arg1 arg2 |
{
first sub-command
second command
for i in $some_list
do
...something with $i...
done
} >$outfile 2>$errfile
|
2,485,058 | 2,485,117 | Equivalent to window.setTimeout() for C++ | In javascript there's this sweet, sweet function window.setTimeout( func, 1000 ) ; which will asynchronously invoke func after 1000 ms.
I want to do something similar in C++ (without multithreading), so I put together a sample loop like:
#include <stdio.h>
struct Callback
{
// The _time_ this function will be executed.
double execTime ;
// The function to execute after execTime has passed
void* func ;
} ;
// Sample function to execute
void go()
{
puts( "GO" ) ;
}
// Global program-wide sense of time
double time ;
int main()
{
// start the timer
time = 0 ;
// Make a sample callback
Callback c1 ;
c1.execTime = 10000 ;
c1.func = go ;
while( 1 )
{
// its time to execute it
if( time > c1.execTime )
{
c1.func ; // !! doesn't work!
}
time++;
}
}
How can I make something like this work?
| Make Callback::func of type void (*)(), i.e.
struct Callback
{
double execTime;
void (*func)();
};
You can call the function this way:
c1.func();
Also, don't busy-wait. Use ualarm on Linux or CreateWaitableTimer on Windows.
|
2,485,120 | 2,485,131 | C++ cin problems. not capturing input from user | I have the following method which is not capturing anything from the user.If I input New Band for the artist name, it only captures "New" and it lefts out "Band". If I use cin.getline() instead nothing is captured. Any ideas how to fix this?
char* artist = new char [256];
char * getArtist()
{
cout << "Enter Artist of CD: " << endl;
cin >> artist;
cin.ignore(1000, '\n');
cout << "artist is " << artist << endl;
return artist;
}
This worked just fine. Thank you Roger
std::string getArtist()
{
cout << "Enter Artist of CD: " << endl;
while(true){
if ( getline(cin, artist)){
}
cout << "artist is " << artist << '\n';
}
return artist;
}
| std::string getArtist() {
using namespace std;
while (true) {
cout << "Enter Artist of CD: " << endl;
string artist;
if (getline(cin, artist)) { // <-- pay attention to this line
if (artist.empty()) { // if desired
cout << "try again\n";
continue;
}
cout << "artist is " << artist << '\n';
return artist;
}
else if (cin.eof()) { // failed due to eof
// notice this is checked only *after* the
// stream is (in the above if condition)
// handle error, probably throw exception
throw runtime_error("unexpected input error");
}
}
}
The whole thing is a general improvement, but the use of getline is possibly the most significant for your question.
void example_use() {
std::string artist = getArtist();
//...
// it's really that simple: no allocations to worry about, etc.
}
|
2,485,190 | 2,485,202 | How to edit the first line in a text file in c++? | I have a text file looks like this :
100 50 20 90
4.07498 0.074984
37.1704 28.1704
20.3999 14.3999
48.627 35.627 ....
I need to edit this file so that everything is kept the same except the first line, 3rd item. The ouput should look like this:
100 50 19 90
4.07498 0.074984
37.1704 28.1704
20.3999 14.3999
48.627 35.627
....
How can I do it in c++ ? Can anybody help me?
Thanks,
Hoang
| #include <stdio.h>
int main()
{
FILE *pFile;
pFile = fopen("example.txt", "r+");
fseek(pFile, 7, SEEK_SET);
fputs("19", pFile);
fclose(pFile);
return 0;
}
Edit: The above was of course mostly a joke. The real way to do it is to read the first line, split it into parts, change the required number, write it out, then follow with all the rest of the lines. If we know that the file contains four integers (floats?) on the first line, something like this might suffice:
#include <fstream>
#include <iostream>
using namespace std;
int main ()
{
ifstream in("in.txt");
ofstream out("out.txt");
float v1, v2, v3, v4;
in >> v1 >> v2 >> v3 >> v4;
v3 = 19.1234; // <- Do whatever you need to here.
out << v1 << " " << v2 << " " << v3 << " " << v4;
out << in.rdbuf();
out.close();
in.close();
return 0;
}
|
2,485,284 | 2,485,297 | getline(cin, variable) not wanting to work properly in c++? | Here's my program so far:
int main()
{
char choice = 'D';
string inputString;
cout << "Please input a string." << endl;
getline(cin, inputString);
LetterCount letterCount(inputString);
while(choice != 'E')
{
cout << "Please choose from the following: " << endl
<< "A) Count the number of vowels in the string." << endl
<< "B) Count the number of consonants in the string." << endl
<< "C) Count both the vowels and consonants in the string." << endl
<< "D) Enter another string." << endl << "E) Exit the program." << endl;
cin >> choice;
if(choice == 'A' || choice == 'a')
{
cout << "There are " << letterCount.vowelCount() << " vowels in this string." << endl;
}
else if(choice == 'B' || choice == 'b')
{
cout << "There are " << letterCount.consonantCount() << " consonants in this string." << endl;
}
else if(choice == 'C' || choice == 'c')
{
cout << "There are " << letterCount.vowelCount() << " vowels and " << letterCount.consonantCount()
<< " consonants in this string, for a total of " << (letterCount.vowelCount() + letterCount.consonantCount())
<< " letters." << endl;
}
else if(choice == 'D' || choice == 'd')
{
cout << "Please type in another string." << endl;
getline(cin, inputString);
letterCount.setInputString(inputString);
}
else
{
choice = 'E';
}
}
}
I'm only including the main as it's the issue giver here, everything else functions properly.
The problem comes up when I use choice 'D' (input a new string.) as soon as enter is hit, the program returns right to the choice prompt and sets the inputString variable to blank (not the word blank, but nothing in it)
the first getline(cin, inputString) works perfectly fine, the second one is the issue giver...any suggestions?
| i think you have to add something like this:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
after your cin >> choice
The reason for this is, that the user actually entered 'D\n' but only 'D' fits into the choice variable, so the '\n' goes into the buffer of cin.
when you call getline, getline sees that '\n' in the buffer and returns with nothing in it...
that call above will remove all '\n' which are in the cin buffer.
Its explained quite well here
another solution would be something like:
char newline;
cin >> choice;
cin.get(newline);
This will only remove a single '\n' from the buffer.. (since cin >> choice added one \n)
|
2,485,336 | 2,487,756 | Address of function is not actual code address | Debugging some code in Visual Studio 2008 (C++), I noticed that the address in my function pointer variable is not the actual address of the function itself. This is an extern "C" function.
int main() {
void (*printaddr)(const char *) = &print; // debug shows printaddr == 0x013C1429
}
Address: 0x013C4F10
void print() {
...
}
The disassembly of taking the function address is:
void (*printaddr)(const char *) = &print;
013C7465 C7 45 BC 29 14 3C 01 mov dword ptr [printaddr],offset print (13C1429h)
EDIT: I viewed the code at address 013C4F10 and the compiler is apparently inserting a "jmp" instruction at that address.
013C4F10 E9 C7 3F 00 00 jmp print (013C1429h)
There is actually a whole jump table of every method in the .exe.
Can someone expound on why it does this? Is it a debugging "feature" ?
| That is caused by 'Incremental Linking'. If you disable that in your compiler/linker settings the jumps will go away.
http://msdn.microsoft.com/en-us/library/4khtbfyf(VS.80).aspx
|
2,485,388 | 2,485,412 | Heuristic to identify if a series of 4 bytes chunks of data are integers or floats | What's the best heuristic I can use to identify whether a chunk of X 4-bytes are integers or floats? A human can do this easily, but I wanted to do it programmatically.
I realize that since every combination of bits will result in a valid integer and (almost?) all of them will also result in a valid float, there is no way to know for sure. But I still would like to identify the most likely candidate (which will virtually always be correct; or at least, a human can do it).
For example, let's take a series of 4-bytes raw data and print them as integers first and then as floats:
1 1.4013e-45
10 1.4013e-44
44 6.16571e-44
5000 7.00649e-42
1024 1.43493e-42
0 0
0 0
-5 -nan
11 1.54143e-44
Obviously they will be integers.
Now, another example:
1065353216 1
1084227584 5
1085276160 5.5
1068149391 1.33333
1083179008 4.5
1120403456 100
0 0
-1110651699 -0.1
1195593728 50000
These will obviously be floats.
PS: I'm using C++ but you can answer in any language, pseudo code or just in english.
| You are going to be looking at the upper 8 or 9 bits. That's where the sign and mantissa of a floating point value are. Values of 0x00 0x80 and 0xFF here are pretty uncommon for valid float data.
In particular if the upper 9 bits are all 0 then this likely to be a valid floating point value only if all 32 bits are 0. Another way to say this is that if the exponent is 0, the mantissa should also be zero. If the upper bit is 1 and the next 8 bits are 0, this is legal, but also not likely to be valid. It represents -0.0 which is a legal floating point value, but a meaningless one.
To put this into numerical terms. if the upper byte is 0x00 (or 0x80), then the value has a magnitude of at most 2.35e-38. Plank's constant is 6.62e-34 m2kg/s that's 4 orders of magnitude larger. The estimated diameter of a proton is much much larger than that (estimated at 1.6e−15 meters). The smallest non-zero value for audio data is about 2.3e-10. You aren't likely to see floating point values are are legitimate measurements of anything real that are smaller than 2.35e-38 but not zero.
Going the other direction if the upper byte is 0xFF then this value is either Infinite, a NaN or larger in magnitude than 3.4e+38. The age of the universe is estimated to be 1.3e+10 years (1.3e+25 femtoseconds). The observable universe has roughly e+23 stars, Avagadro's number is 6.02e+23. Once again float values larger than e+38 rarely show up in legitimate measurements.
This is not to say that the FPU can't load or produce such values, and you will certainly see them in intermediate values of calculations if you are working with modern FPUs. A modern FPU will load a floating point value that has a exponent of 0 but the other bits are not 0. These are called denormalized values. This is why you are seeing small positive integers show up as float values in the range of e-42 even though the normal range of a float only goes down to e-38
An exponent of all 1s represents Infinity. You probably won't find infinities in your data, but you would know better than I. -Infinity is 0xFF800000, +Infinity is 0x7F800000, any value other than 0 in the mantissa of Infinity is malformed. malformed infinities are used as NaNs.
Loading a NaN into a float register can cause it to throw an exception, so you want to use integer math to do your guessing about whether your data is float or int until you are fairly certain it is int.
|
2,485,495 | 2,485,515 | Are there any Netbooks powerful enough for moderate C++ compilation? | I've tried a few Asus Ones, and found that even switching between multiple windows could take seconds. Is there anything powerful enough in that form factor for C++ programmers to build small to moderate size projects?
| I also give it a qualified yes.
What OS you use may matter a lot. I have Kubuntu on a HP 2140 netbook with only 1 gb of ram and the usual Asus N270 cpu. And it is actually rather snappy for window or desktop switches etc under KDE 4.3.
Compile-times are ok but I am spoiled by better machines at the office or even at home. But I got this for the form factor and I take it with me while commuting. I mostly edit, write docs, etc pp while I am on the train and then commit back to SVN at the other end. That works well for me, including the occassional make or make check.
|
2,485,503 | 2,492,162 | Embedding cg shaders in C++ GPGPU library | I'm writing a GPGPU Fluid simulation, which runs using C++/OpenGL/Cg. At the moment, the library requires that the user specify a path to the shaders, which is will then read it from.
I'm finding it extremely annoying to have to specify that in my own projects and testing, so I want to make the shader contents linked in with the rest.
Ideally, my .cg files would still be browsable seperately, but a post-build step or pre-processor directive would include it in the source when required.
To make things slightly more annoying, I have a "utils" shader file, which contains functions that are shared among things (like converting 3d texture coords to the 2d atlas equivalent).
I'd like a solution that's cross platform if possible, but it's not so big a deal, as it is currently windows-only. My searches have only really turned up objcopy for linux, but using that for windows is less than ideal.
If it helps, the project is available at http://code.google.com/p/fluidic
| You mean you want the shaders embedded as strings in your binary? I'm not aware of any cross-platform tools/libraries to do that, which isn't that surprising because the binaries will be different formats.
For Windows it sounds like you want to store them as a string resource. You can then read the string using LoadString(). Here's how to add them, but it doesn't look like you can link them to a file.
A particularly hacky but cross-platform solution might be to write a script to convert your shaders into a string constant in a header. Then you can just #include it in your code.
I.e. you have the file myshader.shader which contains:
int aFunction(int i, int j)
{
return i/j;
}
And you have a build step that creates the file myshader.shader.h which looks like:
const char[] MYSHADER_SHADER =
"int aFunction(int i, int j)"
"{"
" return i/j;"
"}";
Then add #include "myshader.shader.h" to your code.
Very hacky, but I see no reason why it wouldn't work (except for maybe length/space limits on string literals).
Update: With the release of G++ 4.5 it supports C++0x raw string literals. These can contain new lines 4. I haven't tested it but you should be able to do something like this:
const char[] MY_SHADER = R"qazwsx[
#include "my_shader.c"
]qazwsx";
I haven't tested it though.
|
2,485,565 | 2,485,570 | C++ print value of a pointer | I have an array of double pointers, but every time I try do print one of the values the address gets printed. How do I print the actual value?
cout << arr[i] ? cout << &arr[i] ? they both print the address
Does anyone know?
| If it's really an array of (initialized) double pointers, i.e.:
double *arr[] = ...
// Initialize individual values
all you need is:
cout << *arr[i];
|
2,485,614 | 2,485,626 | going reverse in a for loop? | Basically i got this for loop and i want the number inputed (eg. 123) to be printed out in reverse, so "321".
so far it works fine and prints out the correct order when the for loop is
for(i = 0; i<len ; i++)
but i get an error when i try to print it in reverse?. Whats going wrong?
#include <stdio.h>
#include <string.h>
void cnvrter(char *number);
int main(){
char number[80];
printf("enter a number ");
gets(number);
cnvrter(number);
return 0;
}
void cnvrter(char *number){
char tmp[80];
int i = 0,len = 0;
int cnvrtd_digit = 0;
len = strlen(number);
printf("\nsize of input %d\n",len);
for(i = len; i>len ; i--){
if ( ( number[i] >= '0' ) && ( number[i]<='9' ) ){
tmp[0] = number[i];
sscanf(tmp,"%d",&cnvrtd_digit);
}
printf("%d\n",cnvrtd_digit);
}
}
| Look at your for loop again:
for(i = len; i>len ; i--){
You're doing i=len, and then testing for i>len -- unless something goes seriously wrong in the assignment, that's never going to be true...
By the way, though it's not related, you shouldn't be using gets, even in a program like this that you never intend to put to serious use.
|
2,485,869 | 2,486,238 | How to read registry correctly for multiple values in c? | I created a .dll which should work like the RunAs command. The only difference is, that it should read from registry. My problem is, that i need to reed 3 values from the registry, but i can't. It reads the first, than it fails at the second one (Password) with error code 2, which means "The system cannot find the file specified". If i query only for domain and username then it is ok, if i query only for password then it it still succeeds, but if i want to query all three then it fails. Can someone tell me, what i am doing wrong?
Heres my code:
HKEY hKey = 0;
DWORD dwType = REG_SZ;
DWORD dwBufSize = sizeof(buf);
TCHAR szMsg [MAX_PATH + 32];
HANDLE handle;
LPVOID lpMsgBuf;
if( RegOpenKeyEx( HKEY_CURRENT_USER, TEXT("SOFTWARE\\Kampi Corporation\\RunAs!"), 0, KEY_QUERY_VALUE, &hKey ) == ERROR_SUCCESS )
{
if( RegQueryValueEx( hKey, TEXT("Username"), 0, &dwType, (LPBYTE)buf, &dwBufSize ) == ERROR_SUCCESS )
{
memset( szMsg, 0, sizeof( szMsg ) );
wsprintf ( szMsg, _T("%s"), buf );
mbstowcs( wuser, szMsg, 255 );
RegCloseKey( hKey );
}
else
{
MessageBox ( pCmdInfo->hwnd, "Can not query for Username key value!", _T("RunAs!"), MB_ICONERROR );
RegCloseKey( hKey );
return -1;
}
}
else
{
CSimpleShlExt::showerror( GetLastError(), pCmdInfo->hwnd, "RegOpenKeyEx failed for Username with error code :: " );
return -1;
}
if( RegOpenKeyEx( HKEY_CURRENT_USER, TEXT("SOFTWARE\\Kampi Corporation\\RunAs!"), 0, KEY_QUERY_VALUE ,&hKey ) == ERROR_SUCCESS )
{
if( RegQueryValueEx( hKey, TEXT("Password"), 0, &dwType, (LPBYTE)buf, &dwBufSize ) == ERROR_SUCCESS )
{
memset( szMsg, 0, sizeof( szMsg ) );
wsprintf ( szMsg, _T("%s"), buf );
mbstowcs( wpass, szMsg, 255 );
RegCloseKey( hKey );
}
else
{
char test[200];
sprintf(test,"Can not query for Password key value! EC: %d",GetLastError() );
MessageBox ( pCmdInfo->hwnd, test, _T("RunAs!"), MB_ICONERROR );
RegCloseKey( hKey );
return -1;
}
}
else
{
CSimpleShlExt::showerror( GetLastError(), pCmdInfo->hwnd, "RegOpenKeyEx failed for Password with error code :: " );
return -1;
}
if( RegOpenKeyEx( HKEY_CURRENT_USER, TEXT("SOFTWARE\\Kampi Corporation\\RunAs!"), 0, KEY_QUERY_VALUE ,&hKey ) == ERROR_SUCCESS )
{
if( RegQueryValueEx( hKey, TEXT("Domain"), 0, &dwType, (LPBYTE)buf, &dwBufSize ) == ERROR_SUCCESS )
{
memset( szMsg, 0, sizeof( szMsg ) );
wsprintf ( szMsg, _T("%s"), buf );
mbstowcs( wdomain, szMsg, 255 );
RegCloseKey( hKey );
}
else
{
sprintf(test,"Can not query for Password key value! EC: %d",GetLastError() );
MessageBox ( pCmdInfo->hwnd, test, _T("RunAs!"), MB_ICONERROR );
RegCloseKey( hKey );
return -1;
}
}
else
{
CSimpleShlExt::showerror( GetLastError(), pCmdInfo->hwnd, "RegOpenKeyEx failed for Domain with error code :: " );
return -1;
}
| I think I can see why. You need to initialize dwBufSize each time before you call RegQueryValueEx. This function returns the number bytes copied to buf.
You will find the function returns ERROR_MORE_DATA. You've made the mistake of using GetLastError(). Don't do that. The Reg functions return an error code directly.
|
2,485,899 | 2,485,909 | C++ sort array of char pointers | Can you tell me what's wrong with my method? I ends up putting the same thing everywhre and it's actually not sorting.
void sortArrays(){
int i, j;
for(i=0; i<counter; i++){
for( j=0; j<i; j++){
if( strcmp(title_arr[i], title_arr[j]) < 0){
char* title_temp = title_arr[i];
title_arr[j] = title_temp;
}
}
}
| This:
char* title_temp = title_arr[i];
title_arr[j] = title_temp;
Is equivalent to:
title_arr[j] = title_arr[i];
You never swap them, you just copy one to the other. You should add this line:
title_arr[i] = title_arr[j];
In between the two. That way, you'll overwrite [i] with [j], but _temp still holds the old value of [i], so you can copy that value into [j], thus swapping them.
I suppose it's also a time for a lesson on algorithms. Your algorithm is known as a "bubble sort" algorithm. It is known for it's simplicity, but in a realistic setting it is known for it's inefficiency (the technical term is "teh sux", and the real technical term is O(n^2) ("N squared") performance). Some more common (and more efficient) algorithms include Quicksort, merge sort, and Heapsort, among many others. For more about measuring algorithmic scalability, see the article on Big Oh notation.*
But, as vava pointed out in a comment, unless your assignment is to write your own sorting function, you're going to get better performance with qsort (in C) or std::sort (in C++).
int mystrsort(const void *a, const void *b)
{
return strcmp(*(const char **)a, *(const char **)b);
}
// later:
qsort(title_arr, sizeof title_arr / sizeof(char *), sizeof(char *), mystrsort);
I'm not going to stab at std::sort, but it's going to work about the same (perhaps easier).**
*Note that anyone who likes is free to change these Wikipedia links to Stack Overflow links. It would be better to link to SO, I just linked to Wikipedia because I knew how to find the info I needed faster.
**Note that anyone who likes is free to add a std::sort example. I'm just not sufficiently familiar with C++.
|
2,485,977 | 2,485,983 | Operator overloading in C++ | If you overload - like operator-(), it is to be used to the left of the object, however overloading () like operator()() it is used to the right of the object. How do we know which operator is to be used on the left and which ones to be used on the right?
| Look at the operator precedence chart. This will tell you the direction the operator associates (binds). Note that some operators have multiple forms with different meanings, such as binary and unary -. In such cases, you may have multiple overloads, e.g.:
T operator-()
and:
T operator-(const T &o)
The compiler chooses the right one based on the syntactical interpretation of the operator.
See also this useful set of guidelines.
|
2,486,034 | 2,486,055 | delete[] an array of objects | I have allocated and array of Objects
Objects *array = new Objects[N];
How should I delete this array?
Just
delete[] array;
or with iterating over the array's elements?
for(int i=0;i<N;i++)
delete array[i];
delete[];
Thanks
UPDATE:
I changed loop body as
delete &array[i];
to force the code to compile.
| Every use of new should be balanced by a delete, and every use of new[] should be balanced by delete[].
for(int i=0;i<N;i++)
delete array[i];
delete[] array;
That would be appropriate only if you initialized the array as:
Objects **array = new Objects*[N];
for (int i = 0; i < N; i++) {
array[i] = new Object;
}
The fact that your original code gave you a compilation error is a strong hint that you're doing something wrong.
BTW, obligatory: avoid allocating arrays with new[]; use std::vector instead, and then its destructor will take care of cleanup for you. Additionally it will be exception-safe by not leaking memory if exceptions are thrown.
|
2,486,060 | 2,488,290 | Tips on how to deploy C++ code to work every where | I'm not talking about making portable code. This is more a question of distribution. I have a medium-sized project. It has several dependencies on common libraries (eg openssl, zlib, etc). It compiles fine on my machine and now it's time to give it to the world.
Essentially build engineering at its finest. I want to make installers for Windows, Linux, MacOSX, etc. I want to make a downloadable tar ball that will make the code work with a ./configure and a make (probably via autoconf). It would be icing on the cake to have a make option that would build the installers..maybe even cross-compile so a Windows installer could be built in Linux.
What is the best strategy? Where can I expect to spend the most time? Should the prime focus be autoconf or are there other tools that can help?
| I would recommend CMake. Advantages:
It is very easy to use for building simple and complex projects with static libraries, dynamic libraries, executables and their dependencies.
It is platform independent and generates makefiles and/or ide project files for most compilers and IDEs.
It abstracts the differences between windows and unix, eg "libShared.so" and "Shared.dll" are referred to as "Shared" (cmake handles the name differences for each platform), if Shared is part of your project it sorts out the dependency if not it assumes that it is in the linker path.
It investigates the users system for compiler and 3rd party libraries that are required, you can then optionally remove components when 3rd party libraries are not available or display an error message (It ships with macros to find most common 3rd party libraries).
It can be run from the command line or with a simple gui that enables the user to change any of the parameters that were discovered above (eg compiler or version of 3rd party library).
It supports macros for automating common steps.
There is a component called CPack that enables you to create an installer, I think this is just a make install command line thing (I have not used it).
The CTest component integrates with other unit testing libraries like boost test or google test.
I use CMake for everything now, even simple test projects with visual studio.
I have never used autotools but a lot of other users have commented that cmake is easier to use. The KDE project moved to cmake from autotools for this reason.
|
2,486,128 | 2,486,137 | Why aren't return types considered in Java method overloads? | Why return type of a method is not considered in method overloading ?
Can somebody explain , how compiler checks for overloaded methods ?
|
Why return type of a method is not considered in method overloading?
The main reason is that if you did consider this, a lot of function calls become ambiguous if the return value is not assigned to something. For example, which function call is being invoked here?
public String x() { ... }
public int x() { ... }
// ...
x(); // <-- Which one did you mean? It's impossible to tell if you
// allow return types to be part of method overloads.
There are other reasons to not want to do this, too. That said, many languages do allow their signatures to differ only in return type; Haskell and Perl are two examples. If your language does allow this, it's not hard to see that all you'd need to support this is one more step in your method-resolution process: simply have an obvious way for the compiler to select one method or another. In the example above, perhaps we would define a priority (maybe the first method defined is the one that wins, for example, so our x() call would invoke String x()).
Another thing to note is that the JVM does allow two methods whose signature differs only in return type to exist. (That's how Scala and other JVM languages that support this do it.
|
2,486,386 | 2,486,395 | Why do I see THROW in a C library? | When I do:
less /usr/include/stdio.h (which is only a C library - nothing to do with C++)
I see __THROW after quite a few function declarations.
Also, comments above a few functions say that 'This function is a possible cancellation point and therefore not marked with __THROW'
What is all this for?
throw is meant to be for exception handling...but as far as I know, C doesn't provide any support for it.
Please explain.
| This header is likely shared between the C and C++ compiler for that vendor. Did you look what __THROW is defined as?
I suspect something akin to:
#ifdef __cplusplus
#define __THROW throw()
#else
#define __THROW
#endif
Or for actual specifications:
#ifdef __cplusplus
#define __THROW(x) throw(x)
#else
#define __THROW(x)
#endif
As you can see, in a C build, it expands to nothing. In C++, it does what you expect. This allows vendors to reuse the same file.
Just to nitpick, this isn't entirely true: "(which is only a C library - nothing to do with C++)"
The C++ standard library includes the ability to use the C standard library. The actual header is <cxxx> where xxx is the C header name. That is, to include the C header <stdlib.h> in C++, you do <cstdlib>. So it does have to do with C++. :)
This is why you see the code you do. Duplicating the header for two different languages would be a nightmare for maintenance and cleanliness.
|
2,486,406 | 2,486,463 | how to exploit vulnerability of php? | I have never seen a buffer overflow exploit in live action. Suppose I found a server that seems to have vulnerabilities. Where can I get proof of the concept code preferably in c/c++ to exploit the vulnerability? eg I found this vulnerability
Multiple directory traversal vulnerabilities in
functions such as 'posix_access()', 'chdir()', 'ftok()'
may allow a remote attacker to bypass 'safe_mode'
restrictions. (CVE-2008-2665 and CVE-2008-2666).
How can I get proof of concept code for educational purposes
PS
I am a student and my only desire is to learn
| I believe you have somewhat failed to understand the nature of the directory traversal bug.
safe_mode in PHP means that only local filepaths are allowed to be open, rather than allowing any recognizeable protocol such as for example http:// paths. The safe_mode check that verifies wether or not the path is a local file can be tricked to accept HTTP URLs (and other protocols) and wrongfully identifying them as local paths, there by allowing a range of security holes depending on the exact implementation (but remote code inclusion or XSS attacks are what comes to mind).
In general you use PHP scripts to exploit PHP bugs, since the bugs are actually in the interpreter. A buffer overflow can't really occur in your PHP code, but rather in some specific function of the PHP compiler and to exploit it you need to either find a script that calls that function with a user supplied argument (i.e. browse through popular open source software) or simple create your own intentional exploit script and upload to the location you wish to exploit, for example your webhosting provider.
When it comes to bugs in the PHP interpreter it's essentially the webserver/PHP module you're exploiting via PHP function calls, not through written exploits (unless they are simply applications doing HTTP requests to the PHP site).
|
2,486,410 | 2,486,425 | Extra leading zeros when printing float using printf? | I'd like to be able to write a time string that looks like this: 1:04:02.1 hours using printf.
When I try to write something like this:
printf("%d:%02d:%02.1f hours\n", 1, 4, 2.123456);
I get:
1:04:2.1 hours
Is it possible to add leading zeros to a float formatting?
| With the %f format specifier, the "2" is treated as the minimum number of characters altogether, not the number of digits before the decimal dot. Thus you have to replace it with 4 to get two leading digits + the decimal point + one decimal digit.
printf("%d:%02d:%04.1f hours\n", 1, 4, 2.123456);
|
2,486,451 | 2,486,612 | Design question - loading info from DB | I need to build a class that will represent a row in some table in DB (lets say the table is 'Subscriber' and so is the class).
I can have the class Subscriber which constructor receives the Objectkey of subscriber, retrieves info from DB and initializes its members.
I add another class - SubscriberLoader which have a static method 'LoadSubscriber'. This method will receive the subscriber objectkey, retrieve info from DB, crate a Subscriber object and initialize its members. Subscriber constructor will be private and SubscirberLoader will be friend class of Subscriber - this way, client could build a Subscriber only using the loader.
which of the two is better? any other suggestions?
| I'd recommend the second approach, because it separates two concerns into two separate classes:
the concern of whatever a subscriber is supposed to do
the concern of extracting a subscriber from the database
|
2,486,493 | 2,486,627 | invasive vs non-invasive ref-counted pointers in C++ | For the past few years, I've generally accepted that
if I am going to use ref-counted smart pointers
invasive smart pointers is the way to go
--
However, I'm starting to like non-invasive smart pointers due to the following:
I only use smart pointers (so no Foo* lying around, only Ptr)
I'm starting to build custom allocators for each class. (So Foo would overload operator new).
Now, if Foo has a list of all Ptr (as it easily can with non-invasive smart pointers).
Then, I can avoid memory fragmentation issues since class Foo move the objects around (and just update the corresponding Ptr).
The only reason why this Foo moving objects around in non-invasive smart pointers being easier than invasive smart pointers is:
In non-invasive smart pointers, there is only one pointer that points to each Foo.
In invasive smart pointers, I have no idea how many objects point to each Foo.
Now, the only cost of non-invasive smart pointers ... is the double indirection. [Perhaps this screws up the caches].
Does anyone have a good study of expensive this extra layer of indirection is?
EDIT: by smart pointers, I may be referring to what others call "shared-pointers"; the whole idea is: there is a reference-count attached to objects, and when it hits 0, the object is automatically deleted
| There are several important difference between invasive or non-invasive pointers:
The biggest advantage of second (non-invasive):
It is much simpler to implement weak reference to second one (i.e. shared_ptr/weak_ptr).
Advantage of first is when you need to get smart pointer on this (at least in case of boost::shared_ptr, std::tr1::shared_ptr)
You can't use shared_ptr from this in constructor and destructor.
It is quite non-trivial to have shared_from this in the hierarchy of classes.
|
2,486,713 | 2,488,297 | User defined conversion operator as argument for printf | I have a class that defined a user defined operator for a TCHAR*, like so
CMyClass::operator const TCHAR*() const
{
// returns text as const TCHAR*
}
I want to be able to do something like
CMyClass myClass;
_tprintf(_T("%s"), myClass);
or even
_tprintf(_T("%s"), CMyClass(value));
But when trying, printf always prints (null) instead of the value. I have also tried a normal char* operator, as well variations with const etc.
It only works correctly if I explicitly call the operator or do a cast, like
_tprintf(_T("%s\n"), (const TCHAR*)myClass);
_tprintf(_T("%s\n"), myClass.operator const TCHAR *());
However, I don't want to cast. How can this be achieved?
Note, that a possibility is to create a function that has a parameter of const TCHAR*, so that it forcible calls the operator TCHAR*, but this I also don't want to implement.
| Avoid conversion operators. They rarely do what you want, and then explicit calls are painful. Rename operator const TCHAR*() const to TCHAR *str() const.
|
2,486,727 | 2,486,741 | breaking out from socket select | I have a loop which basically calls this every few seconds (after the timeout):
while(true){
if(finished)
return;
switch(select(FD_SETSIZE, &readfds, 0, 0, &tv)){
case SOCKET_ERROR : report bad stuff etc; return;
default : break;
}
// do stuff with the incoming connection
}
So basically for every few seconds (which is specified by tv), it reactivates the listening.
This is run on thread B (not a main thread). There are times when I want to end this acceptor loop immediately from thread A (main thread), but seems like I have to wait until the time interval finishes..
Is there a way to disrupt the select function from another thread so thread B can quit instantly?
| The easiest way is probably to use pipe(2) to create a pipe and add the read end to readfds. When the other thread wants to interrupt the select() just write a byte to it, then consume it afterward.
|
2,486,963 | 2,487,029 | microsoft visual studio 2008 builds keep failing | My builds keep failing with the following error
Project : error PRJ0002 : Error result 31 returned from 'C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\mt.exe'.
I find that i have to kill some process called mspdbsrv.exe description:"microsoft program database" Then rebuild the entire project. This is annoying. Is there a permanent solution to this problem or is it stuck with me for good?
PS
OS: windows 7 ultimate
msv studio 2008 + sp1 professional
| The problem is that for some reason, your mspdbsrv.exe is staying alive after the build. This is what's used to generate your .pdb files as part of the build. The only reliable solution seems to be to kill that process.
What you can do is at least automate that, just add a post-build event and console kill it. I'd suggest using the SysInternals PSKill utility (free) like this in your post-build:
pskill mspdbsrv.exe
|
2,487,010 | 2,487,043 | Memory allocation problem C/Cpp Windows critical error | I have a code that need to be "translated" from C to Cpp, and i cant understand, where's a problem. There is the part, where it crashes (windows critical error send/dontSend):
nDim = sizeMax*(sizeMax+1)/2;
printf("nDim = %d sizeMax = %d\n",nDim,sizeMax);
hamilt = (double*)malloc(nDim*sizeof(double));
printf("End hamilt alloc. %d allocated\n",(nDim*sizeof(double)));
transProb = (double*)malloc(sizeMax*sizeMax*sizeof(double));
printf("End transProb alloc. %d allocated\n",(sizeMax*sizeMax*sizeof(double)));
eValues = (double*)malloc(sizeMax*sizeof(double));
printf("eValues allocated. %d allocated\n",(sizeMax*sizeof(double)));
eVectors = (double**)malloc(sizeMax*sizeof(double*));
printf("eVectors allocated. %d allocated\n",(sizeMax*sizeof(double*)));
if(eVectors) for(i=0;i<sizeMax;i++) {
eVectors[i] = (double*)malloc(sizeMax*sizeof(double));
printf("eVectors %d-th element allocated. %d allocated\n",i,(sizeMax*sizeof(double)));
}
eValuesPrev = (double*)malloc(sizeMax*sizeof(double));
printf("eValuesPrev allocated. %d allocated\n",(sizeMax*sizeof(double)));
eVectorsPrev = (double**)malloc(sizeMax*sizeof(double*));
printf("eVectorsPrev allocated. %d allocated\n",(sizeMax*sizeof(double*)));
if(eVectorsPrev) for(i=0;i<sizeMax;i++) {
eVectorsPrev[i] = (double*)malloc(sizeMax*sizeof(double));
printf("eVectorsPrev %d-th element allocated. %d allocated\n",i,(sizeMax*sizeof(double)));
}
Log:
nDim = 2485 sizeMax = 70
End hamilt alloc. 19880 allocated
End transProb alloc. 39200 allocated
eValues allocated. 560 allocated
eVectors allocated. 280 allocated
So it crashes at the start of the loop of allocation. If i delete this loop it crashes at the next line of allocation. Does it mean that with the numbers like this i have not enough memory??
Thank you.
| On my machine, this program compiles, executes without error and reports no memory problems when run through valgrind. Unless you are running on a small embedded system, your problem is likely something external to this code, because the total amount of memory allocated by this program is less than 140 KiB.
Besides, when malloc fails, it doesn't crash, it returns NULL. This code properly checks for eVectorsPrev being NULL, so there should be no NULL dereferencing problems here.
|
2,487,143 | 2,487,149 | How can I make this function act like an l-value? | Why can't I use the function ColPeekHeight() as an l-value?
class View
{
public:
int ColPeekHeight(){ return _colPeekFaceUpHeight; }
void ColPeekHeight( int i ) { _colPeekFaceUpHeight = i; }
private:
int _colPeekFaceUpHeight;
};
...
{
if( v.ColPeekHeight() > 0.04*_heightTable )
v.ColPeekHeight()-=peek;
}
The compiler complains at v.ColPeekHeight()-=peek. How can I make ColPeekHeight() an l-value?
| Return the member variable by reference:
int& ColPeekHeight(){ return _colPeekFaceUpHeight; }
To make your class a good one, define a const version of the function:
const int& ColPeekHeight() const { return _colPeekFaceUpHeight; }
when I declare the function with the
two consts
When you want to pass an object into a function that you don't expect it to modify your object. Take this example:
struct myclass
{
int x;
int& return_x() { return x; }
const int& return_x() const { return x; }
};
void fun(const myclass& obj);
int main()
{
myclass o;
o.return_x() = 5;
fun(o);
}
void fun(const myclass& obj)
{
obj.return_x() = 5; // compile-error, a const object can't be modified
std::cout << obj.return_x(); // OK, No one is trying to modify obj
}
If you pass your objects to functions, then you might not want to change them actually all the time. So, to guard your self against this kind of change, you declare const version of your member functions. It doesn't have to be that every member function has two versions! It depends on the function it self, is it modifying function by nature :)
The first const says that the returned value is constant. The second const says that the member function return_x doesn't change the object(read only).
|
2,487,509 | 3,166,936 | Are C++ exceptions sufficient to implement thread-local storage? | I was commenting on an answer that thread-local storage is nice and recalled another informative discussion about exceptions where I supposed
The only special thing about the
execution environment within the throw
block is that the exception object is
referenced by rethrow.
Putting two and two together, wouldn't executing an entire thread inside a function-catch-block of its main function imbue it with thread-local storage?
It seems to work fine, albeit slowly. Is this novel or well-characterized? Is there another way of solving the problem? Was my initial premise correct? What kind of overhead does get_thread incur on your platform? What's the potential for optimization?
#include <iostream>
#include <pthread.h>
using namespace std;
struct thlocal {
string name;
thlocal( string const &n ) : name(n) {}
};
struct thread_exception_base {
thlocal &th;
thread_exception_base( thlocal &in_th ) : th( in_th ) {}
thread_exception_base( thread_exception_base const &in ) : th( in.th ) {}
};
thlocal &get_thread() throw() {
try {
throw;
} catch( thread_exception_base &local ) {
return local.th;
}
}
void print_thread() {
cerr << get_thread().name << endl;
}
void *kid( void *local_v ) try {
thlocal &local = * static_cast< thlocal * >( local_v );
throw thread_exception_base( local );
} catch( thread_exception_base & ) {
print_thread();
return NULL;
}
int main() {
thlocal local( "main" );
try {
throw thread_exception_base( local );
} catch( thread_exception_base & ) {
print_thread();
pthread_t th;
thlocal kid_local( "kid" );
pthread_create( &th, NULL, &kid, &kid_local );
pthread_join( th, NULL );
print_thread();
}
return 0;
}
This does require defining new exception classes derived from thread_exception_base, initializing the base with get_thread(), but altogether this doesn't feel like an unproductive insomnia-ridden Sunday morning…
EDIT: Looks like GCC makes three calls to pthread_getspecific in get_thread. EDIT: and a lot of nasty introspection into the stack, environment, and executable format to find the catch block I missed on the first walkthrough. This looks highly platform-dependent, as GCC is calling some libunwind from the OS. Overhead on the order of 4000 cycles. I suppose it also has to traverse the class hierarchy but that can be kept under control.
| In the playful spirit of the question, I offer this horrifying nightmare creation:
class tls
{
void push(void *ptr)
{
// allocate a string to store the hex ptr
// and the hex of its own address
char *str = new char[100];
sprintf(str, " |%x|%x", ptr, str);
strtok(str, "|");
}
template <class Ptr>
Ptr *next()
{
// retrieve the next pointer token
return reinterpret_cast<Ptr *>(strtoul(strtok(0, "|"), 0, 16));
}
void *pop()
{
// retrieve (and forget) a previously stored pointer
void *ptr = next<void>();
delete[] next<char>();
return ptr;
}
// private constructor/destructor
tls() { push(0); }
~tls() { pop(); }
public:
static tls &singleton()
{
static tls i;
return i;
}
void *set(void *ptr)
{
void *old = pop();
push(ptr);
return old;
}
void *get()
{
// forget and restore on each access
void *ptr = pop();
push(ptr);
return ptr;
}
};
Taking advantage of the fact that according to the C++ standard, strtok stashes its first argument so that subsequent calls can pass 0 to retrieve further tokens from the same string, so therefore in a thread-aware implementation it must be using TLS.
example *e = new example;
tls::singleton().set(e);
example *e2 = reinterpret_cast<example *>(tls::singleton().get());
So as long as strtok is not used in the intended way anywhere else in the program, we have another spare TLS slot.
|
2,487,534 | 2,487,627 | Subtracting months/years from boost::posix_time::ptime | I have a boost::posix_time::ptime that points to March 31st 2010 like this:
ptime p(date(2010, Mar, 31));
I would like to subtract a month (and possibly years) from this date. From the docs I see these two operators: ptime operator-(time_duration) and ptime operator-(days) but none of them can work with months/years. If I try and do:
time_duration duration = hours(24 * 30);
ptime pp = p - duration;
I'm getting March 1st and if I'm trying:
ptime pp = p - days(30);
I'm still getting March 1st, while I'd like to get February 28th.
How can I achieve my desired result? (I would like to get the desired result also when subtracting a month from March 28, 29, 30)
| boost::posix_time::ptime::date() operator returns date object. You can call greg_year, greg_month etc. for this object.
|
2,487,608 | 2,487,641 | what is wrong here? associativity? evaluation order? how to change order? | The associativity of stream insertion operator is rtl, forgetting this fact sometimes cause to runtime or logical errors.
for example:
1st-
int F()
{
static int internal_counter c=0;
return ++c;
}
in the main function:
//....here is main()
cout<<”1st=”<<F()<<”,2nd=”<<F()<<”,3rd=”<<F();
and the output is:
1st=3,2nd=2,3rd=1
that is different from what we expect at first look.
2nd-
suppose that we have an implementation of stack data structure like this:
//
//... a Stack<DataType> class ……
//
Stack<int> st(10);
for(int i=1;i<11;i++)
st.push(i);
cout<<st.pop()<<endl<<st.pop()<<endl<<st.pop()<<endl<<st.pop()<<endl;
expected output is something like:
10
9
8
7
but we have:
7
8
9
10
There is no internal bug of << implementation but it can be so confusing...
and finally[:-)] my question: is there any way to change associativity of an operator by overloading it?
do you think this could be not reverse? i mean is it possible to change order by modifying or changing an open source STL?
| The only things that are right-associative are the assignment operators. See §5.4 to 5.18 of the standard. The << operators are evaluated left-to-right or the messages would be backward in grammar, not in content. The content is due to side effects, which are unordered in C++ except (as Neil mentions) for "short-circuit" && and ||, and comma.
|
2,487,653 | 2,487,739 | Avoiding denormal values in C++ | After searching a long time for a performance bug, I read about denormal floating point values.
Apparently denormalized floating-point values can be a major performance concern as is illustrated in this question:
Why does changing 0.1f to 0 slow down performance by 10x?
I have an Intel Core 2 Duo and I am compiling with gcc, using -O2.
So what do I do? Can I somehow instruct g++ to avoid denormal values?
If not, can I somehow test if a float is denormal?
| You can test whether a float is denormal using
#include <cmath>
if ( std::fpclassify( flt ) == FP_SUBNORMAL )
(Caveat: I'm not sure that this will execute at full speed in practice.)
In C++03, and this code has worked for me in practice,
#include <cmath>
#include <limits>
if ( flt != 0 && std::fabsf( flt ) < std::numeric_limits<float>::min() ) {
// it's denormalized
}
To decide where to apply this, you may use a sample-based analyzer like Shark, VTune, or Zoom, to highlight the instructions slowed by denormal values. Micro-optimization, even more than other optimizations, is totally hopeless without analysis both before and after.
|
2,487,838 | 2,487,856 | Qt: default value of variable in class | When creating my own class in Qt I would like my variables in the class to have a standard/default value if I haven't set them to anything. It would be perfect if this was possible to set in the h-file so I don't have to do it in each instance method of my class. You can see what I want to do in the code below. In the example myBool would have the value of false and myInt the value of 0 when the object have been created. Is this possible at all?
In myclass.h:
class MyClass
{
Q_OBJECT
public:
MyClass();
~MyClass();
bool myBool = false; //I want to set myBool and myInt to a default/standard value
int myInt = 0;
};
| Qt follows the rules of C++, and one rule is to use constructors to initialize your members.
MyClass::MyClass() : myBool(false), myInt(0)
{
}
|
2,487,911 | 2,494,122 | Connecting Arduino to the Internet across a firewall proxy | I have an Arduino with an Ethernet Shield.
How can I connect it to the Internet across a firewall proxy?
For example, the Arduino Ethernet library has only this reference to demonstrate how to connect your board to the Internet but no clue how to do it across firewall proxies, etc.
Repeated from Arduino help pages.
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 10, 0, 0, 177 };
byte server[] = { 64, 233, 187, 99 }; // Google
Client client(server, 80);
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
if (client.connect()) {
Serial.println("connected");
client.println("GET /search?q=arduino HTTP/1.0");
client.println();
} else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
}
As can be seen, there is no way here to resolve my TCP connections across a firewall proxy.
Also I am just curious how this whole process of TCP connection is resolved across a firewall proxy in the above context, please put some suitable reference too.
| The Client class supports neither SOCKS nor HTTP proxies. You'll have to modify the code in Ethernet.h yourself.
|
2,487,931 | 5,979,028 | LLVM C++ IDE for Windows | Is there some C/C++ IDE for Windows, which is integrated with the LLVM compiler (and Clang C/C++ analyzer), just like modern Xcode do.
I have Dev-Cpp (it uses outdated GCC) and Code::Blocks (with some GCC). But GCC gives me very cryptic error messages. I want to get some more user-friendly error messages from the Clang frontend.
Yes, Clang was not able to be used with complex C++ code, but trunk Clang already can compile LLVM itself. So I wonder if is there any of LLVM IDEs in development or in beta versions.
Yes, I can use Clang as other compiler with GCC-compatible IDEs. But is there any IDE, that are integrated with Clang? Clang have a different output format, so the IDE must parse it. Clang can provide IDE parsing of sources. Clang has an analyze option, which must be supported in an IDE. Take a look, e.g http://iosdevelopertips.com/xcode/static-code-analysis-clang-and-xcode-3-2.html
And the most wanted feature of Clang - is smart auto-completion, so the IDE can suggest only syntaxilly-correct variants, e.g. list only fields of this struct, class.
Results: (merged from answers):
Eclipse with CDT>=8 and with https://code.google.com/archive/p/llvm4eclipsecdt/ plugin, from Petri Tuononen (no smart auto-completion)
Vim with vimrc from the LLVM project (smart completion only?) https://llvm.org/viewvc/llvm-project/llvm/trunk/utils/vim/
Emacs with (smart completion only?) https://llvm.org/svn/llvm-project/cfe/trunk/utils/clang-completion-mode.el
Qt Creator: https://blog.qt.io/blog/2011/10/19/qt-creator-and-clang/
CodeLite: http://www.codelite.org/LiteEditor/ClangIntegration35
| LLVM is supported in Eclipse CDT via plug-in (llvm4eclipsecdt). It is the only Windows supported IDE supporting LLVM as far as I know. I am the main author of the plug-in so you can ask any questions related to it.
The plug-in offers the basic functionality for Clang and llvm-gcc compilation and support Linux and Windows (w/ Cygwin & MiNGW). LLVM tools such as assembler, archiver, linker, and static compiler (llc) are configured and can be customized via UI. The plug-in offers all the benefits that IDE can offer such as easy configuration and building with one action.
The only drawback is that it is not ready yet as it lacks of some of the advanced features that LLVM can offer such as Clang analyze and smart auto-completion. The plug-in is also not tested well and may not work perfectly therefore I hope I can get user feedback via mailing list found from Google code development site (listed below). I wish I had time to develop it further. I only develop it in my spare time, which is very limited. I welcome any developers to participate and contribute to the project.
Development site:
http://code.google.com/p/llvm4eclipsecdt/
https://github.com/TuononenP/llvm4eclipsecdt
Eclipse marketplace (100% free & open-source):
http://marketplace.eclipse.org/content/llvm-toolchain-eclipse-cdt
UPDATE: The plugin is deprecated. Instead install "C/C++ LLVM-Family Compiler Build Support" under Programming Languages using the official Eclipse update site e.g. http://download.eclipse.org/releases/mars
|
2,488,199 | 2,488,370 | MinGW Doesn't Generate an Object File When Compiling | I've just bought a new laptop for me on the travel, then on my free time, I've started to test MinGW on it by trying to compile my own OS that is written in C++, then I've created all the files needed and the kernel.cpp:
extern "C" void _main(struct multiboot_data* mbd, unsigned int magic);
void _main( struct multiboot_data* mbd, unsigned int magic )
{
char * boot_loader_name =(char*) ((long*)mbd)[16];
/* Print a letter to screen to see everything is working: */
unsigned char *videoram = (unsigned char *) 0xb8000;
videoram[0] = 65; /* character 'A' */
videoram[1] = 0x07; /* forground, background color. */
}
And tried to compile it with g++
G:> g++ -o C:\kernel.o -c kernel.cpp -Wall -Wextra -Werror -nostdlib -nostartfiles -nodefaultlibs
kernel.cpp: In function `void _main(multiboot_data*, unsigned int)':
kernel.cpp:8: warning: unused variable 'boot_loader_name'
kernel.cpp: At global scope:
kernel.cpp:4: warning: unused parameter 'magic'
G:>
But it don't create any binary file at C:/>.
What can I do?
| It doesn't create the file because you have -Werror enabled. The warnings you're getting about unused variables are counting as errors, so compilation gets aborted. Just comment them out for the moment:
void _main( struct multiboot_data* mbd, unsigned int /* magic */ )
{
// char * boot_loader_name =(char*) ((long*)mbd)[16];
// ...
}
And it should build fine. Also, shouldn't _main() be declared as just main() and then allowed to be "mangled" into _main() by the compiler? Edit: You probably also want to be using -c to skip the linking phase, assuming you just want the object files.
|
2,488,317 | 2,488,329 | The problem of return reference to local variable |
Possible Duplicate:
Returning reference to a local variable
I happened to find this code return 5. It's OK to write it this way or should definitely be avoid?
int& f() {
int i = 5;
return i;
}
int main(){
cout<<f()<<endl;
}
| If it works, it works only by accident. This is undefined behavior and should definitely be avoided.
The moment that f returns, there are no longer any guarantees as to what happens to the memory where i lived and what happens when you try to access it.
|
2,488,330 | 2,488,348 | Is it possible to Serialize and Deserialize objects in C++? | As we know c++ is also an Object Oriented Programming language where most the things are objects like java. So wanted to know is the Serialize and deserializ features are available in c++ as well as we do it in java?
If yes how it can be achieved?
In java We use Serializable Interface to say that this type of object can be serialized and deserialized.
So in c++ how?
And out of curiosity is it same in c# as in java?
| Check this out:
http://www.functionx.com/cpp/articles/serialization.htm
or use
Boost:Serialization
http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/index.html
|
2,488,385 | 2,544,943 | Where to get streaming (live) video and audio from camera example app for Nokia? | Where to get streaming (live) video and audio from camera example for Nokia (5800 for ex)?
Suppose I want to create some live video streaming service app so I'll have some cool server at the back end. And I know how to do that part. Suppose I have some stand alone app for PCs now I want to go on to mobile devices. So I decided to start from Nokia because I have it and can do with it what I want (Nokia 5800 XpressMusic). So I want to see some sample app grabing audio and video streams from Phone, Synchronizing them, and sending LIVE stream to server. I need any OpenSource sample (JAVA or C or C++) that ll do this or something like this. Where can I get one?
| Do you already know network protocols used to stream media content, like RTSP?
If not, you probably need to start with that.
You should find good code to start with in the Helix source code.
You may face the usual issue of your network mobile operator filtering out anything but HTTP, which is not a very practical protocol for what you want to do.
I wouldn't advise using Java as simply synchronizing audio and video capture will be a nightmare and I wouldn't rely on being able to open a GCF streaming connection.
For Symbian OS C++, I would suggest starting with the multimedia example code from the Quick Recipes book then iterating through the Media Framework plugins installed on your device to see whether one of them can stream video.
If your handset doesn't already have a Media Framework plugin that can do this, you will probably want to give up once you realize that you basically need the handset manufacturer to sign any additional plugin you might want to develop yourself.
At this point, it would be worth going through the Qt documentation and example code since Qt has decent multimedia capability and was first developed with desktop computers in mind.
Video streaming from a mobile phone might also be a bad idea in and of itself, considering the reliance on good network bandwidth to upload lots of data very quickly and the fact that moving the handset while it records video tends to produce bad video quality because of the high video compression used to keep bitrates at a minimum.
|
2,488,406 | 2,488,507 | Why doesn't c++ have &&= or ||= for booleans? | Is there a "very bad thing" that can happen &&= and ||= were used as syntactic sugar for bool foo = foo && bar and bool foo = foo || bar?
| A bool may only be true or false in C++. As such, using &= and |= is relatively safe (even though I don’t particularly like the notation). True, they will perform bit operations rather than logical operations (and thus they won’t short-circuit) but these bit operations follow a well-defined mapping, which is effectively equivalent to the logical operations, as long as both operands are of type bool.1
Contrary to what other people have said here, a bool in C++ must never have a different value such as 2. When assigning that value to a bool, it will be converted to true as per the standard.
The only way to get an invalid value into a bool is by using reinterpret_cast on pointers:
int i = 2;
bool b = *reinterpret_cast<bool*>(&i);
b |= true; // MAY yield 3 (but doesn’t on my PC!)
But since this code results in undefined behaviour anyway, we may safely ignore this potential problem in conforming C++ code.
1 Admittedly this is a rather big caveat as Angew’s comment illustrates:
bool b = true;
b &= 2; // yields `false`.
The reason is that b & 2 performs integer promotion such that the expression is then equivalent to static_cast<int>(b) & 2, which results in 0, which is then converted back into a bool. So it’s true that the existence of an operator &&= would improve type safety.
|
2,488,418 | 2,488,525 | Should I pointer-cast from a private derived class to its base class? | I found this from C++FAQ
Generally, No.
From a member function or friend of a
privately derived class, the
relationship to the base class is
known, and the upward conversion from
PrivatelyDer* to Base* (or
PrivatelyDer& to Base&) is safe; no
cast is needed or recommended.
However users of PrivatelyDer should
avoid this unsafe conversion, since it
is based on a private decision of
PrivatelyDer, and is subject to change
without notice.
How to understand the above words? I don't think the explanation is correct or accurate.
I have a code like this
class A{
};
class B: private A{
};
int main(){
B *b = new B();
A *a = new A();
a = b; //wrong
a = (A*)b; //right
}
| From a purely mechanical viewpoint, you're right: a cast to a private base class will work and produce working results.
The point of the FAQ is that from a design viewpoint it's generally wrong. Private inheritance is really supposed to mean private -- in other words, even though it may work, you're not supposed to know it'll work, and at some point it may quit working -- since it's officially an implementation detail, not part of the public interface, they could re-implement the class without using inheritance. At that point, the cast wouldn't work any more (but because you've used a cast, the compiler probably won't warn you about it having gone from something you probably shouldn't do to something that can't possibly work at all).
Edit: Yes, the cast does necessarily work. According to §5.4/7 of the standard:
... the following static_cast and
reinterpret_cast operations
(optionally followed by a const_cast
operation) may be performed using the
cast notation of explicit type
conversion, even if the base class
type is not accessible:
— a pointer to an object of derived
class type or an lvalue of derived
class type may be explicitly converted
to a pointer or reference to an
unambiguous base class type,
respectively;
[emphasis added]
|
2,488,513 | 2,488,542 | How do debug header file implemetation (its .cpp) in c++ using GDB | I have these 3 file in my program:
sample1.h (method in sample1.cpp are defined here)
sample1.cpp (all the actual implementations)
demo.cpp (I am using the methods in sampe1.cpp here, and have included sample1.h)
Now, I am using GDB to debug and I know the basic commands like "break lineno." or "break methodname". But, how do I debug the methods written in sample1.cpp?
I tried: break "sample1.cpp:mymethod" but it did not work.
| try
break mymethod
As the function name in not ambiguous, it should work.
See. http://www.unknownroad.com/rtfm/gdbtut/gdbbreak.html#BCPPFUNC
|
2,488,515 | 2,488,553 | Official names for pointer operators | What are the official names for the operators * and & in the context of pointers? They seem to be frequently called dereference operator and address-of operator respectively, but unfortunately, the section on unary operators in the standard does not name them.
I really don't want to name & address-of anymore, because & returns a pointer, not an address. (see below) The standard is very clear about this:
The result of the unary & operator is a pointer to its operand.
Symmetry suggests to name & reference operator which is a little unfortunate because of the collision with references in C++. The fact that & returns a pointer suggests pointer operator. Are there any official sources that would confirm these (or other) namings?
pointers vs. addresses
A pointer is a language mechanism, while an address is an implementation detail. Addresses are untyped, while pointers aren't, except for void*. Kevlin Henney also distinguishes between pointers and addresses in an Interview:
C [...] allows us to abstract the specifics of the machine to the point that we are talking about pointers and not addresses. There is a whole load of pain that you no longer have to go through.
| From the C99 draft, at the index:
* (indirection operator), 6.5.2.1, 6.5.3.2
& (address operator), 6.3.2.1, 6.5.3.2
From the C++0x draft, at the index:
*, see indirection operator, see multiplication operator
&, see address-of operator, see bitwise AND operator
It's also referenced in 9.6/3 "The address-of operator & shall not be applied to a bit-field, so there are no pointers to bit-fields."
(So, sorry, you still need to call & "address-of" :p)
Personally I don't care the actual name as long as other can understand what I'm saying. I just call * "star" and & "and". :)
|
2,488,545 | 2,488,653 | Reading bmp file for steganography | I am trying to read a bmp file in C++(Turbo). But i m not able to print binary stream.
I want to encode txt file into it and decrypt it.
How can i do this. I read that bmp file header is of 54 byte. But how and where should i append txt file in bmp file. ?
I know only Turbo C++, so it would be helpfull for me if u provide solution or suggestion related to topic for the same.
int main()
{
ifstream fr; //reads
ofstream fw; // wrrites to file
char c;
int random;
clrscr();
char file[2][100]={"s.bmp","s.txt"};
fr.open(file[0],ios::binary);//file name, mode of open, here input mode i.e. read only
if(!fr)
cout<<"File can not be opened.";
fw.open(file[1],ios::app);//file will be appended
if(!fw)
cout<<"File can not be opened";
while(!fr)
cout<<fr.get(); // error should be here. but not able to find out what error is it
fr.close();
fw.close();
getch();
}
This code is running fine when i pass txt file in binary mode
EDIT :
while(!fr)
cout<<fr.get();
I am not able to see binary data in console
this was working fine for text when i was passing character parameter in fr.get(c)
| I think you question is allready answered:
Print an int in binary representation using C
convert your char to an int and you are done (at least for the output part)
|
2,488,596 | 2,488,604 | How to return a copy of the data in C++ | I am trying to return a new copy of the data in a C++ Template class. The following code is getting this error: invalid conversion from 'int' to 'int*'. If I remove the new T then I am not returning a copy of the data but a pointer to it.
template<class T>
T OrderedList<T>::get( int k )
{
Node<T>* n = list;
for( int i = 0; i < k; i++ )
{
n=n->get_link();
}
return new T( n->get_data() ); // This line is getting the error **********
}
| new creates and returns a pointer. You just want a copy which will be created implicitly, since the return statement will invoke the copy constructor (or equivalent for POD) of the object T:
return n->get_data();
|
2,488,730 | 2,489,409 | pyopengl: Could it replace c++? | I'm starting a computer graphics course, and I have to choose a language.
Choices are between C++ and Python. I have no problem with C++, python is a work in progress. So i was thinking to go down the python road, using pyopengl for graphics part.
I have heard though, that performance is an issue.
Is python / pyopengl mature enough to challenge C++ on performance?
I realize its a long shot, but I'd like to hear your thoughts, experiences on uses of pyopengl.
| It depends a LOT on the contents of your computer graphics course. If you are doing anything like the introductory course I've taught in the past, it's basically spinning cubes and spheres, some texture mapping and some vertex animation, and that's about it. In this case, Python would be perfectly adequate, assuming you can get around the Unpythonic (and, lets be honest, un-C++) OpenGL state-machine paradigm.
For things like doing your matrix maths you can use Numpy, the core of which is written in C and is really quite quick. You'll be up and running faster, iterate faster and most likely have more fun.
If, however, you are doing some hardcore, cutting edge, millions-of-triangles-per-scene-skinned-animated-everything computer graphics course, stick with C++.
If your class has given you the choice it's probably a safe bet that Python will be ok.
If you want to leverage your knowledge into a real job in computer graphics though, pretty much every game and graphics engine is written in C or C++, while Python (or Lua) is left as a scripting language.
|
2,488,782 | 2,488,812 | Some questions about Vector in STL | I have some questions about vector in STL to clarify.....
Where are the objects in vector allocated? heap?
does vector have boundary check? If the index out of the boundary, what error will happen?
Why array is faster than vector?
Is there any case in which vector is not applicable but array is a must?
|
In a contiguous memory block on the heap. A vector<int> allocates memory the same way new int[x] would.
Only if you use the at method. It throws an std::out_of_range exception if the boundary check fails. The operator[] doesn't perform bounds checking.
Because an array gives direct access to memory, while accessing a vector element most likely involves a method call. The difference can be ridiculously small though, especially if your compiler decides to inline the calls.
In general, you'll use a vector if you want your container to have a dynamic size, and a simple array if a known fixed size is enough. Be sure to check out the other containers, like deque and list, to be sure you pick the most appropriate one. Otherwise, if you need to deal with non-C++ APIs, you'll obviously need to have access to a regular array. (edit) @BillyONeal says you should use &vector[0] to get the address of the underlying array, but use it with care since it can change if the vector's capacity changes.
|
2,488,915 | 2,488,929 | why no += operator for vectors in stl | I am curious? What high fundu logic goes behind not implementing:
result+=vector1;
where both result and vector1 are stl vectors.
Note: i know how to implement that bit, but i need to know what logic, the sages who designed STL were using when they chose not to implement this feature?
| What are you expecting result to contain, the result of concatenating the original result with vector1 or an element-wise += (whatever that means for the underlying types), possibly default-initializing members if the sizes don't match?
And yes, this is an answer ;) .
Operator overloading should only be used where the meaning of the operation is unambiguous and practical for the underlying type and where it would offer a significant notational brevity over appropriately named function calls.
Note that valarray has more operator overloads than vector due to its interface and intended use.
|
2,488,941 | 2,488,957 | Find which numbers appears most in a vector | I have some numbers stored in a std::vector<int>. I want to find which number appears most in the vector.
e.g. in the vector
1 3 4 3 4 2 1 3 2 3
the element that occurs the most is 3.
Is there any algorithm (STL or whatever) that does this ?
| Sort it, then iterate through it and keep a counter that you increment when the current number is the same as the previous number and reset to 0 otherwise. Also keep track of what was the highest value of the counter thus far and what the current number was when that value was reached. This solution is O(n log n) (because of the sort).
Alternatively you can use a hashmap from int to int (or if you know the numbers are within a limited range, you could just use an array) and iterate over the vector, increasing the_hashmap[current_number] by 1 for each number. Afterwards iterate through the hashmap to find its largest value (and the key belonging to it). This requires a hashmap datastructure though (unless you can use arrays which will also be faster), which isn't part of STL.
|
2,489,128 | 2,489,159 | GCC emits extra code for boost::shared_ptr dereference | I have the following code:
#include <boost/shared_ptr.hpp>
struct Foo { int a; };
static int A;
void
func_shared(const boost::shared_ptr<Foo> &foo) {
A = foo->a;
}
void
func_raw(Foo * const foo) {
A = foo->a;
}
I thought the compiler would create identical code, but for shared_ptr version an extra seemingly redundant instruction is emitted.
Disassembly of section .text:
00000000 <func_raw(Foo*)>:
0: 55 push ebp
1: 89 e5 mov ebp,esp
3: 8b 45 08 mov eax,DWORD PTR [ebp+8]
6: 5d pop ebp
7: 8b 00 mov eax,DWORD PTR [eax]
9: a3 00 00 00 00 mov ds:0x0,eax
e: c3 ret
f: 90 nop
00000010 <func_shared(boost::shared_ptr<Foo> const&)>:
10: 55 push ebp
11: 89 e5 mov ebp,esp
13: 8b 45 08 mov eax,DWORD PTR [ebp+8]
16: 5d pop ebp
17: 8b 00 mov eax,DWORD PTR [eax]
19: 8b 00 mov eax,DWORD PTR [eax]
1b: a3 00 00 00 00 mov ds:0x0,eax
20: c3 ret
I'm just curious, is this necessary, or it is just an optimizer's shortcoming?
Compiling with g++ 4.1.2, -O3 -NDEBUG.
| It's not a 'redundant' instruction.
The relevant section of the first code snippet is equivalent to:
*p
Whilst in the second it's equivalent to:
**p
Due to shared_ptr's internals there is a second level of indirection. This is not something the optimizer can 'fix'.
At any rate, the difference is negligible.
EDIT:
Whoops! My apologies, I misread your code.
You are passing the shared_ptr BY REFERENCE in your code. That will pass it "by pointer" at the ASM level.
So you're passing a pointer to a shared_ptr, and that shared_ptr contains a pointer to your object.
Hence the two levels of indirection.
Sorry for the confusion. :)
|
2,489,197 | 2,489,235 | What's the best way to resolve a filepath? | I've got a series of filepaths that look something like this:
C:\Windows\System32\svchost.exe -k LocalSystemNetworkRestricted
C:\Windows\System32\svchost
C:\Program Files (x86)\Common Files\Steam\SteamService.exe /RunAsService
"C:\Program Files (x86)\Common Files\Steam\SteamService.exe" /RunAsService
and I need to find these paths' actual locations. So, respectively, the above would be:
C:\Windows\System32\svchost.exe
C:\Windows\System32\svchost.exe
C:\Program Files (x86)\Common Files\Steam\SteamService.exe
C:\Program Files (x86)\Common Files\Steam\SteamService.exe
What's the best way to go about doing this? Does windows have an API function to accomplish it? I essentially am trying to figure out what executable CreateProcess will call if I pass it that path.
Thanks!
Billy3
EDIT: This is the code I settled on for now:
#include <algorithm>
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>
#include <Windows.h>
namespace Path {
bool Exists(const std::wstring& path)
{
DWORD result = GetFileAttributesW(path.c_str());
return result != INVALID_FILE_ATTRIBUTES;
}
#define PATH_PREFIX_RESOLVE(path, prefix, environment) \
if (boost::algorithm::istarts_with(path, prefix)) { \
ExpandEnvironmentStringsW(environment, buffer, MAX_PATH); \
path.replace(0, (sizeof(prefix)/sizeof(wchar_t)) - 1, buffer); \
if (Exists(path)) return path; \
}
std::wstring Resolve(std::wstring path)
{
using namespace boost::algorithm;
wchar_t buffer[MAX_PATH];
trim(path);
if (path.empty() || Exists(path)) return path;
//Start by trying to see if we have a quoted path
if (path[0] == L'"') {
return std::wstring(path.begin() + 1, std::find(path.begin() + 1, path.end(), L'"'));
}
//Check for those nasty cases where the beginning of the path has no root
PATH_PREFIX_RESOLVE(path, L"\\", L"");
PATH_PREFIX_RESOLVE(path, L"?\?\\", L"");
PATH_PREFIX_RESOLVE(path, L"\\?\\", L"");
PATH_PREFIX_RESOLVE(path, L"globalroot\\", L"");
PATH_PREFIX_RESOLVE(path, L"system32\\", L"%systemroot%\\System32\\");
PATH_PREFIX_RESOLVE(path, L"systemroot\\", L"%systemroot%\\");
static std::vector<std::wstring> pathExts;
if (pathExts.empty()) {
#define MAX_ENVVAR 32767
wchar_t pathext[MAX_ENVVAR];
DWORD length = GetEnvironmentVariableW(L"PATHEXT", pathext, MAX_ENVVAR);
if (!length) WindowsApiException::ThrowFromLastError();
split(pathExts, pathext, std::bind2nd(std::equal_to<wchar_t>(), L';'));
pathExts.insert(pathExts.begin(), std::wstring());
}
std::wstring::iterator currentSpace = path.begin();
do {
currentSpace = std::find(currentSpace, path.end(), L' ');
std::wstring currentPath(path.begin(), currentSpace);
std::wstring::size_type currentPathLength = currentPath.size();
typedef std::vector<std::wstring>::const_iterator ExtIteratorType;
for(ExtIteratorType it = pathExts.begin(); it != pathExts.end(); it++) {
currentPath.replace(currentPathLength, currentPath.size() - currentPathLength, *it);
if (Exists(currentPath)) return currentPath;
}
if (currentSpace != path.end())
currentSpace++;
} while (currentSpace != path.end());
return path;
}
}
| Number 4 should be relatively easy. If the path starts with a " character, just read until the next " and that's the path. With the others, it's slightly more tricky, but the way Windows does it is by simply breaking the command line into parts, and trying one at a time, so looking at #3, it breaks it up into an array like this:
["C:\Program", "Files", "(x86)\Common", "Files\Steam\SteamService.exe", "/RunAsService"]
Then it simply starts from the left-most element and looks for files:
C:\Program
C:\Program Files
C:\Program Files (x86)\Common
C:\Program Files (x86)\Common Files\Stream\StreamService.exe
C:\Program Files (x86)\Common Files\Steam\SteamService.exe /RunAsService
Each step, it checks whether a file with that name exists. If so, that's the one it chooses. It also tries appending ".exe" to the name. So in the first step, it checks whether there is a file called "C:\Program.exe" and if so, that's the first. If not, it moves to the second step and tries "C:\Program Files.exe". If that doesn't exist, it moves to the next one and so on.
There have been issues in the past with how this algorithm works, for example, see here.
|
2,489,314 | 2,489,360 | Why is casting Derived** to Base*const* forbidden? | After reading this question, i saw the answer by Naveen containing a link to this page, which basically says, that casting from Derived** to Base** is forbidden since could change a pointer to an pointer to a Derived1 object point to a pointer to a Derived2 object (like: *derived1PtrPtr=derived2Ptr).
OK, i understand this is evil ...
But when casting Derived** to Base*const* this is not even possible, so whats the reason that this is not allowed anyway ?
| First thing is that, if you really need to, you can cast any pointer type to any other pointer type. For instance, you can cast to void* as an intermediate step.
Second, with pointers-to-pointers, it's not so much that there's a reason to make particular cases hard as that there are no special rules to make any particular cases easy.
Basically, you have a pointer to X - where X in your case happens to be another pointer. Some X cases get special treatment (e.g. derived classes can implicitly cast to bases) - but your X is not one of them. It's not the base class - it's a pointer. There are no implicit casts defined for derived**, other than to void* - you can't even implicitly cast derived** to void**.
I don't think the const has much to do with it in this case, though I could be missing something.
|
2,489,321 | 2,489,350 | Static Function Help C++ | I can't get past this issue I am having. Here's a simple example:
class x
{
public:
void function(void);
private:
static void function2(void);
};
void x::function(void)
{
x::function2(void);
}
static void function2(void)
{
//something
}
I get errors in which complain about function2 being private. If I make it public (which I don't really want to do) I get errors about an undefined reference to function2. What am I doing wrong? Thank you!
|
You can't have a function declaration and definition both in a class. Either move the definitions out of the class or remove the declarations.
You can't call a function with a void as a parameter. That is used only in the declaration.
The function definition for function2 if outside the class will need a x:: qualifier and static is not needed the second time.
class x
{
public:
void function(void);
private:
static void function2(void);
};
void x::function(void)
{
x::function2();
}
void x::function2(void)
{
}
|
2,489,335 | 2,489,485 | What does template<class key, class type> mean before a method in C++? | I have got this code and I am trying to understand the convention followed, all the method defined in the .cpp file have template<class KeyType, class DataType> written before them. What does that mean?
Example:
//Constructor
template<class key, class type>
MyOperation<key, type>::MyOperation()
{
//method implementation
}
//A method
template<class key, class type>
MyOperation<key, type>::otherOperation()
{
//method implementation
}
Thanks
| There has to be a good answer for this already but I'll throw mine into the pool as well.
C++ allows for declarations and implementations of program structures to be done separately. It stems from how C/C++ programmers publish new functionality to each other: header files are included in dependent compilation units rather than those units relying on metadata present in compilation (like you would expect if you work with C# or Java).
Each time you give the compiler an instruction whether it is a declaration ("there will be this thing with this interface") or an implementation ("here is this thing with this interface and these behaviors"), you have an opportunity to templatize that directive.
The fact that you have an option to do so, rather than a requirement to do so, gives you a lot more flexibility than you are afforded by more modern languages such as Java and C#.
Consider the following template (I'm rusty so be kind with minor syntax issues, please):
template<typename Junk>
class IGotJunk {
private:
Junk myJunk_;
public:
void SetJunk(Junk const& source);
Junk const& GetJunk() const;
}
Your "typical" implementation of said template might include these default behaviors:
template<typename Junk>
void IGotJunk<Junk>::SetJunk(Junk const& source)
{
myJunk_ = source;
}
However, for strings, there is a risk that the string will be modified after the pointer is copied, in which case, you could provide a specialized behavior that ensures the string itself is copied, rather than the pointer (again, it's been a long, long time)...
void IGotJunk<char*>::SetJunk(char* const& source)
{
free(myJunk_);
myJunk_ = malloc(strlen(source) + 1);
strcpy(myJunk_, source);
}
You could then do something similar for GetJunk(). That is probably why you have to declare the template parameters for each artifact you create: because you might not want them to be the same in every case.
|
2,489,379 | 2,492,581 | encrypt- decrypt with AES using C/C++ | How can I encrypt and decrypt a file with a 256 key AES in C or C++?
| If you are just after AES and do not mind losing flexibility (i.e. you will not replace it with another cryptographic algorithm at some time) then Brian Gladman's AES implementation is a popular choice (both for performance and portability). This is the kind of code which you embed in your own source code.
On the external libraries front, you have plenty of choice, including NSS, OpenSSL, Crypto++... the latter is specifically designed for C++, while the two others are meant for C.
|
2,489,387 | 2,489,532 | Differing paths for lua script and app | My problem is that I'm having trouble specifying paths for Lua to look in.
For example, in my script I have a require("someScript") line that works perfectly (it is able to use functions from someScript when the script is run standalone.
However, when I run my app, the script fails. I believe this is because Lua is looking in a location relative to the application rather than relative to the script.
Hardcoding the entire path down to the drive isn't an option since people can download the game wherever they like so the highest I can go is the root folder for the game.
We have XML files to load in information on objects. In them, when we specify the script the object uses, we only have to do something like Content/Core/Scripts/someScript.lua where Content is in the same directory as Debug and the app is located inside Debug. If I try putting that (the Content/Core...) in Lua's package.path I get errors when I try to run the script standalone.
I'm really stuck, and am not sure how to solve this. Any help is appreciated. Thanks.
P.S. When I print out the default package.path in the app I see syntax like ;.\?.lua
in a sequence like...
;.\?.lua;c:...(long file path)\Debug\?.lua; I assume the ; means the end of the path, but I have no idea what the .\?.lua means. Any Lua file in the directory?
| You can customize the way require loads modules by putting your own loader into the package.loaders table. See here:
http://www.lua.org/manual/5.1/manual.html#pdf-package.loaders
If you want to be sure that things are nicely sandboxed, you'll probably want to remove all the default loaders and replace them with one that does exactly what you want and nothing more. (It will probably be somewhat similar to one of the existing ones, so you can use those as a guide.)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.