question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,030,562 | 4,030,631 | ADT - Iterators - operator ++ | This isnt a homework question. I took data structures at a Community College and now that i am at the university i talked to the teacher about there data structures class. Now, since its really different and the class i took transferred, He gave me one of there assignments and said play with it. We never did any contai... | I think you should have a look at the iterators in the STL. It will help you for your conception.
About your code, operator++ is declared to return void, which is wrong. You also forgot the other version of operator++, the operator-- and operator-> member functions which are great helpers to use iterators.
Your contain... |
4,030,945 | 4,031,151 | Using SecureZeroMemory in Delphi | I understand there is a SecureZeroMemory function in C.
The function implementation is defined in <WinnNT.h> as RtlSecureZeroMemory function.
QNS: How can SecureZeroMemory be used in Delphi? Did Delphi release a library that contains that function? I'm using Delphi 7. Windows.pas only has ZeroMemory but not SecureZeroM... | As far as I understand, the only difference between ZeroMemory and SecureZeroMemory is SecureZeroMemory is implemented as an inline function, ensuring it won't be optimised out by the compiler.
I don't think Delphi performs the same level of compiler optimisation, so ZeroMemory calls shouldn't be optimised out.
|
4,030,955 | 4,030,978 | Library function returns raw pointer and I want to use smart pointer | I have this situation where the library I use has many functions that return raw pointers to objects, how could I now use boost smart pointers in my program using this library and using smart pointers?
The library is xerces-C++ and an example is getting the document iterator:
boost::shared_ptr<DOMNodeIterator> itera = ... | I guess the library provides a way of releasing those raw pointers ?
If so, you can just "create" a shared_ptr with a custom deleter, specifying the "free function" provided by the library.
Example:
If you have the two functions:
Foo* createFoo();
void freeFoo(Foo* foo);
You can create a shared_ptr that way:
boost::sh... |
4,030,959 | 4,030,983 | Will a "variableName;" C++ statement be a no-op at all times? | In C++ sometimes a variable will be defined, but not used. Here's an example - a function for use with COM_INTERFACE_ENTRY_FUNC_BLIND ATL macro:
HRESULT WINAPI blindQuery( void* /*currentObject*/, REFIID iid, void** ppv, DWORD_PTR /*param*/ )
{
DEBUG_LOG( __FUNCTION__ ); //DEBUG_LOG macro expands to an empty strin... | Yes, but you'll likely get another warning.
The standard way of doing this is: (void)iid;.
Very technically, this could still load iid into a register and do nothing. Granted that's extremely stupid on the compilers part (I doubt any would ever do that, if it does delete the compiler), but it's a more serious issue if... |
4,031,198 | 4,031,360 | kill boost thread after n seconds | I am looking for the best way to solve the following (c++) problem. I have a function given by some framework, which returns an object. Sometimes it takes just miliseconds, but on some occasions it takes minutes. So i want to stop the execution if it takes longer than let's say 2 seconds.
I was thinking about doing it... | As for waiting, just use thread::timed_join() inside your main thread, this will return false, if the thread didn't complete within the given time.
Killing the thread is not feasible if your third-party library is not aware of boost:threads. Also, you almost certainly don't want to 'kill' the thread without giving the ... |
4,031,228 | 4,031,487 | Why is "operator void" not invoked with cast syntax? | While playing with this answer by user GMan I crafted the following snippet (compiled with Visual C++ 9):
class Class {
public:
operator void() {}
};
Class object;
static_cast<void>( object );
(void)object;
object.operator void();
after stepping over with the debugger I found out that casting to void does... | The technical reason why is found in §12.3.2:
A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.
The rat... |
4,031,249 | 4,032,515 | Dll Memory Management | I have few doubts regarding how windows manages a .dll's memory.
when .dll's are loaded into the host
process, how is the memory managed?
Does .dll get access to the entire
memory available to the host process
or just a portion of it? i.e is
there a limitation when memory is
allocated by a function inside the
.dll?
W... | "Memory management" is a split responsibility, typically. The OS hands address space in big chunks to the runtime, which then hands it out in smaller bits to the program. This address space may or may not have RAM allocated. (If not, there will be swap space to back it)
Basically, when a DLL is loaded, Windows allocate... |
4,031,270 | 4,031,337 | Efficient way to remove items from vector | Currently, I plan to remove all items from vector, which is not found in a set.
For example :
#include <vector>
#include <set>
#include <string>
#include <iostream>
using namespace std;
int main() {
std::set<string> erase_if_not_found;
erase_if_not_found.insert("a");
erase_if_not_found.insert("b");
er... | Yes; you can use the erase/remove idiom with a custom predicate:
template <typename SetT>
struct not_contained_in_set_impl
{
not_contained_in_set_impl(const SetT& s) : set_(s) { }
template <typename T>
bool operator()(const T& v)
{
return set_.find(v) == set_.end();
}
const SetT& set_;... |
4,031,408 | 4,053,407 | Using SetWindowText in WIN32 GDI, and securely deleting data typed in | I wish to securely delete (not even a trace in memory) anything that user types into a textbox. I wonder if setting it to "" is secure enough.
SetWindowText is a function in Win32 API, in user32.dll.
In the program:
SetWindowText(myHandle, "Hello");
SetWindowText(myHandle, "Goodbye");
//Was the buffer containing chars... | No, it isn't secure because GDI copies your string multiple times, for example to make it wide-char string: you use SetWindowTextA but it's just a wrapper for SetWindowTextW, so SetWindowTextA copies your string to wide-char string.
For secure solution you should implement your own textbox with custom user input handli... |
4,031,444 | 4,031,524 | How can I execute an SQLite statement in C++ | I have the following command which works fine on Linux Console. But to get the result to a cpp file I have to store it to file and then read it. But is there a way I can directly execute this command in C++.
/usr/bin/sqlite3 /etc/myDB/db/share.db "select path from folder_info where ftp='YES'"
| As far as i understand your question you can use the SQLite3 c++ api which is described here
|
4,031,459 | 4,032,070 | How to convert vector<unsigned char> to int? | I have vector<unsigned char> filed with binary data. I need to take, lets say, 2 items from vector(2 bytes) and convert it to integer. How this could be done not in C style?
| Please use the shift operator / bit-wise operations.
int t = (v[0] << 8) | v[1];
All the solutions proposed here that are based on casting/unions are AFAIK undefined behavior, and may fail on compilers that take advantage of strict aliasing (e.g. GCC).
|
4,031,488 | 4,031,512 | Function arguments push order | Why are function arguments pushed on the stack in right to left order?
| To enable the existence of functions with a variable number of arguments, like printf. The function can extract the first one or two arguments and then use their values to deduce the total number of arguments on the stack.
|
4,031,609 | 4,031,661 | Dumping the memory contents of a object | In a game that I mod for they recently made some changes which broke a specific entity. After speaking with someone who figured out a fix for it, they only information they gave me was that they "patched it" and wouldn't share anymore.
I am basically trying to remember how to dump the memory contents of a class object ... | template <class T>
void dumpobject(T const *t) {
unsigned char const *p = reinterpret_cast<unsigned char const *>(t);
for (size_t n = 0 ; n < sizeof(T) ; ++n)
printf("%02d ", p[n]);
printf("\n");
}
|
4,031,672 | 4,031,835 | Without access to argv[0], how do I get the program name? | I know the program name is passed as the first argument, and next simple example will print it to the standard output :
#include <iostream>
int main ( int argc, char *argv[] )
{
std::cout<<argv[0]<<std::endl;
}
Is there a function to get the program name?
EDIT
I am starting the program from the shell, and the above ... | No, there is no such function. Linux stores the program name in __progname, but that's not a public interface. In case you want to use this for warnings/error messages, use the err(3) functions.
If you want the full path of the running program, call readlink on /proc/self/exe:
char *program_path()
{
char *path = ma... |
4,031,728 | 4,031,847 | Operator = is ambiguous (C++) | I have the following in a for loop and the compiler says 'operator = is ambiguous'. Not sure how to solve this issue, can anyone help?
rootelement = document->getDocumentElement();
boost::interprocess::unique_ptr<DOMNodeIterator, release_deleter> itera (document->createNodeIterator(rootelement, DOMNodeFilter::SHOW... | Like Stephane says, unique_ptr's maintain uniqueness unless you explicitly move them, or assign an rvalue to them. Normally, your code would be fine, but since you're faking rvalues, you'll need to move it explicitly.
I've never used boost::interprocess::unique_ptr, but it looks like you want this:
namespace bi = boost... |
4,031,957 | 4,032,290 | GDB question: Pretty-Printing a 2D Array? | I have a 2d array matrix[10][10] that I'd like to inspect at debug time.
I understand that I can do this in GDB using
p *matrix@10
But it outputs this in one line, making it difficult to read.
Is there a way to have this output formatted in any way, lets say as a matrix?
| An important feature of GDB is the ability of execute functions in the debugged code, so you can implement whatever printing you like, for example:
#include <stdio.h>
int matrix[10][10];
void print(int matrix[10][10]) {
int i, j;
for (i = 0; i < 10; ++i) {
for (j = 0; j < 10; ++j)
printf("%d ", matrix[i... |
4,032,162 | 4,032,706 | C++ compilation error enum "does not name a type" | The following code:
foo.h
#include "bar.h"
class foo{
public:
enum my_enum_type { ONE, TWO, THREE };
foo();
~foo() {}
};
foo.cpp
foo::foo()
{
int i = bar::MY_DEFINE;
}
bar.h
#include "foo.h"
class bar{
public:
static const int MY_DEFINE = 10;
foo::my_enum_type var;
bar() {};
~bar() {};
};
... | You must remove the cyclic dependency so you need to consider foo.cpp and foo.h as different units for this purpose.
bar class definition must see foo::my_enum_type so probably bar.h including foo.h is a necessity.
foo class definition does not use any of bar, so foo.h does not need to include bar.h
foo.cpp does need ... |
4,032,280 | 4,032,470 | Overloading + operator on generic class in C++ | I'm trying to overload the + operator in a forest class, a forest being a collection of trees, and the + operator is supposed to combine two forests into one. I have the following code as my class definition:
template<typename NODETYPE>
class Forest
{
public:
friend Forest& operator+<>(Forest&, Forest&)... | The key to writing operator+ is don't write operator+. Instead, write a copy ctor and operator+=:
template<class NodeType>
struct Forest {
//...
Forest(Forest const &other);
//...
Forest& operator+=(Forest const &other) {
// code here
return *this;
}
//...
};
Now we add operator+:
template<class N... |
4,032,394 | 4,032,688 | What languages/internet protocols for controlling robots/electronics remotely? | I wonder what languages are used in robots and electronics. Is it low level languages like Java, C, C++ etc?
And if these robots and electronics could be controlled from another place, what protocol is used?
It couldn't be HTTP Rest, could it? :)
| How about LEGO Mindstorms? Unless you have specific requirements regarding the physical properties of the robot that would rule out Mindstorms/NXT, you can do a lot with it. And it's a serious piece of kit - don't be fooled by the "LEGO" brand.
http://mindstorms.lego.com/en-us/Default.aspx
In addition to shipping with ... |
4,032,573 | 4,032,644 | Custom Unique_ptr deleter, controlled deleting | I have a for loop that iterates through an XML document and finds a specified attribute, the pointer that points to the current node sits inside a boost::interprocess::unique_ptr and has a custom deletor to call the object's release() function. It seems that on every loop iteration the pointer gets deleted, but the re... | I don't have visual 2010 for compiling and debugging at work, on ly at home. so I cannot be sure.
But Frankly I really do not like the concept that your iterator owns your pointer.
Your collection owns the pointer, the iterator doesn't ! its not its role..
In C++0x there are an complement to shared_ptr that is std::wea... |
4,033,000 | 4,033,106 | Integrating 3rd party C++ compilers with Microsoft Visual Studio | Duplicate issue: I have read this thread and this thread and these didn't quite answer my question.
Question:: Is there a way I could make Visual Studio use g++ or comeau or other as the C++ compiler. If
so, has anyone tried it? Any feedback?
Reason: Love microsoft's IDE, hate their compiler.
| IIRC, Leor Zolman's stlfilt used to provide a drop-in replacement for cl.exe. However, that behaved exactly like cl.exe did. I have seen threads referring to replacing the native cl.exe with one of a different compiler version, and it seems even that could be problematic.
The Windows version of Intel's compiler plugs ... |
4,033,011 | 8,688,526 | CPP Macro: Counter that gives number of instantiations/calls | I want to have a C preprocessor macro that knows the number of instantiations/macro calls of this macro so far.
Example:
int main() {
printf("%d\n", MACRO());
printf("%d\n", MACRO());
}
Should print
0
1
Is something like this possible?
Note that it is not enough to forward this to a function as proposed below.
It... | I happen to have a solution that is similar (in usage) to __COUNTER__ , but is not limited to single counter - you can define many counters as you like.
This one uses gcc-specific feature, but should be able to do similar in other toolchain.
static int getpos(int lineno); // forward declaration
#define MY_COUNTER ({ ... |
4,033,071 | 4,033,248 | Iterate over NULL terminated array of strings using for_each | Iterating over a NULL terminated string using for_each is possible:
const char *name = "Bob";
void func(const char &arg)
{
cout << arg;
}
int main()
{
for_each(name, name + strlen(name), func);
}
Is something similar possible for a NULL terminated list of strings (without having to determine the total length ... | std::for_each "iterates" over a range, so to use it with an array of indeterminate length, you need to use custom iterators to signal the end of the array (on NULL member). If you insist on using NULL-terminated char* array, you could of course create your own for_each function for it, for example like this:
template <... |
4,033,099 | 4,033,167 | using l-value with abstract class | I'm having issue with calling a method with l-value of an abstract class. The class definition is:
class SimulatorSequenceItemBase {
public:
SimulatorSequenceItemBase();
virtual ~SimulatorSequenceItemBase();
virtual uint32_t GetResult(uint32_t p_nSite) = 0;
virtual bool MoveNext(SimulatorSequenceItemBa... | I have no idea what forSeq is supposed to be, but what's wrong with
SimulatorSequenceItemBase& root = forSeq; // note that &
Since, according to a comment, you need to reset root to refer to different objects, you will have to use pointers:
SimulatorSequenceItemBase* root = forSeq; note the *
while(root.MoveNext(roo... |
4,033,487 | 4,033,900 | C++ -- When recompilation is required | You have a class that many libraries depend on. You need to modify the class for one application. Which of the following changes require recompiling all libraries before it is safe to build the application?
add a constructor
add a data member
change destructor into virtual
add an argument with default value to an exis... | Classes are defined in the header file. The header file will be compiled into both the library that implements the class and the code that uses the class. I am assuming that you are taking as a given that you will need to recompile the class implementation after changing the class header file and that the question you ... |
4,033,575 | 4,068,211 | OpenMP parallel on one machine but serial on another | I finally got a section of my code to run in parallel with OpenMP without errors. When I deployed the dll to another machine, however, it no longer ran in parallel.
Logging reveals that omp_in_parallel() == 0 on the other machine but not on mine.
My machine is using an Intel i5 CPU which has 2 hyperthreaded cores for a... | I had enabled OpenMp in Debug mode but not in Release. The deployed dll was in Release mode while I was testing it on my machine in Debug configuration.
You'd think I would have learned after the last time this happened. :-)
Thank you for your answers and my apologies for wasting your time.
|
4,033,953 | 4,034,010 | C++: how to add int to current string in C++? |
Possible Duplicate:
C++ concatenate string and int
Hi,
In C# I can write like this:
int i = 0;
string text = "out.jpg";
while(true)
{
i++;
Object.write(i+text, stream);
}
But this is not true for C++. the problem is at: i + default.
How could I fix this in C++?
Thanks in advance. Your help is much appreci... | You could use a stringstream...
std::stringstream ss;
ss << i << text;
Object.write(ss.str(), stream);
|
4,033,964 | 4,034,191 | C++0x rvalue reference template argument deduction | Given GMan's deliciously evil auto_cast utility function concocted here, I've been trying to figure out why it doesn't compile for me when I'm trying to auto_cast from an rvalue (on MSVC 10.0).
Here's the code that I'm using:
template <typename T>
class auto_cast_wrapper : boost::noncopyable
{
public:
template <t... | You forgot to std::forward the T&& argument to the auto_cast_wrapper constructor. This breaks the forwarding chain. The compiler now gives a warning but it seems to work fine.
template <typename T>
class auto_cast_wrapper
{
public:
template <typename R>
friend auto_cast_wrapper<R> auto_cast(R&& pX);
temp... |
4,033,985 | 4,034,135 | virtual table every instance get's on or every object? | i have read about this metrial and i am still dont understand it's core
e.g:
public static void Main()
{
person []p = new person[]{new student(),new worker()};
}
public class person
{
public void f1() { }
public virtual void f2() { }
}
public class student:person
{
public override void f2() { }
}
... | Virtual table is tied to object's type (i.e. class). But every object (instance of a reference type) has a pointer to its type, and therefore indirectly to its vtable.
If you are interested in C#, there is a neat article here which describes .NET CLR internals: CodeProject .NET Type internals.
|
4,034,308 | 4,034,416 | char* value gets corrupted during assignment | I have the following code , which gets a return value from a function as char*
cDestDrive = ReadFromRegistry(HKEY_CURRENT_USER,NDSPATH,szDestPathRoot);
I am able to read the value inside cDestDrive till the time I am assigning it. The moment I am assigning it:
CString strServerAddress = cDestDrive;
the value of cDe... | I believe you are returning a char* pointing to a an array that is allocated on the stack, i.e. this line:
TCHAR tSZValue[MAX_PATH] = {0};
followed by:
char* cpRegKeyVal=tSZValue;
This is dangerous, and you are experiencing first hand the end result!
EDIT: why don't you directly assign to a CString in the function an... |
4,034,517 | 4,034,670 | How am I supposed to interpret OProfile output? | I tried profiling my application with OProfile recently. The data gathered is already very valuable to me, but I'm having difficulties with its precise interpretation. After running my app with oprofile set up and running, I generated the report and got:
root@se7xeon:src# opreport image:test -l -t 1
Overflow stats n... | When profiling optimized code you really cannot rely on accurate source code lines. The compiler moves stuff around far too much.
For an accurate picture you will need to look at the code disassembler output.
|
4,034,539 | 4,034,635 | Move constructor for a map | I think I do understand "the basic IDEA" of move semantics, but now when I'm on the stage of implementing my own map I stopped and started to think about it when I was going to write a use case and walk through for move ctor of map. Correct me if I'm wrong but what I do understand how the whole business of move semanti... | All you have to do is reassign the Link pointer, since all the other Link pointers are attached to it, they will now be part of the new Map.
Map(Map&& tmp) :impl_(tmp.impl_) { tmp.impl_ = nullptr; }
This is assuming no other data members.
|
4,034,729 | 4,034,916 | GCC/MingW compiling on different versions | I'm wondering can I use static libraries (lib*.a files) compiled with one
version of MingW and use them on the other version ? Or do I have to recompile all libraries ?
| Yes you can. You don't need to recompile them if they are not giving any problems
|
4,034,750 | 4,034,809 | Find all substring's occurrences and locations | I'm writing a program to parse some data saved as text files. What I am trying to do is find the location of every needle in a haystack. I already can read the file in and determine the number of occurrences, but I am looking to find the index also.
| string str,sub; // str is string to search, sub is the substring to search for
vector<size_t> positions; // holds all the positions that sub occurs within str
size_t pos = str.find(sub, 0);
while(pos != string::npos)
{
positions.push_back(pos);
pos = str.find(sub,pos+1);
}
Edit
I misread your post, you said ... |
4,034,895 | 4,035,018 | How to (deep)copy a map from a const object | I have another problem I can't seem to solve..., or find on this site...
I have an object (called DataObject) with a map, declared as follows:
std::map<size_t, DataElement*> dataElements;
Now i have a copy function (used in the copy constructor):
void DataObject::copy(DataObject const &other) {
//here some code t... | std::map<size_t, DataElement*>::const_iterator it = other.dataElements.begin();
while(it != other.dataElements.end())
{
dataElements[it->first] = new DataElement(*(it->second));
++it;
}
I'm almost positive this should work.
|
4,034,908 | 7,918,281 | Fetch-and-add using OpenMP atomic operations | I’m using OpenMP and need to use the fetch-and-add operation. However, OpenMP doesn’t provide an appropriate directive/call. I’d like to preserve maximum portability, hence I don’t want to rely on compiler intrinsics.
Rather, I’m searching for a way to harness OpenMP’s atomic operations to implement this but I’ve hit a... | As of openmp 3.1 there is support for capturing atomic updates, you can capture either the old value or the new value. Since we have to bring the value in from memory to increment it anyways, it only makes sense that we should be able to access it from say, a CPU register and put it into a thread-private variable.
Ther... |
4,035,088 | 4,045,838 | Call methods on class templatized over enum | Given the following code:
enum Fruits{ eApple, eBanana };
template<>
struct SomeFruit< eApple > {
void eatIt() { // eat an apple };
};
template<>
struct SomeFruit< eBanana > {
void eatIt() { // eat a banana };
};
Is there a way to call the explicitly specialized eatIt(), for each of Fruits, without having to... | Firstly thanks to Noah Roberts' answer which deserves as an upvote for being the inspiration to this answer.
Following on from his answer I extracted and refactored boost::mpl::for_each and boost::mpl::range to obtain what I believe is the minimal complete definition which satisfies the question's criteria. It has no ... |
4,035,112 | 4,035,173 | What type should I use for an index variable | This is a best practices question. I am making an array
type * x = malloc(size*sizeof(type));
AFAIK sizeof gives a return value of size_t. Does that mean that I should use a size_t to declare, or pass around size? Also when indexing the array should I also use a size_t for the index variable? What is the best prac... | In general, I use whatever minimizes the number of implicit or explicit casts and warning errors. Generally there is a good reason why things are typed the way they are. size_t is a good choice for array index, since it's unsigned and you don't generally want to access myarray[-1], say.
btw since this is C++ you shou... |
4,035,155 | 4,035,193 | Roman representation of integers |
Possible Duplicate:
How do you find a roman numeral equivalent of an integer
I am looking for a simple algorithm (preferably in Python). How to translate a given integer number to a Roman number?
string Roman(int Num){...}
For example, Roman(1981) must produce "MCMLXXXI".
| I needed the opposite one time (going from Roman numerals to int). Wikipedia has surprisingly detailed information on how Roman numerals work. Once you realize that things are this well-defined and that a specification is available this easily, translating it to code is fairly trivial.
|
4,035,180 | 4,035,231 | Advantages of an empty class in C++ | What could be the possible advantages/uses of having an empty class?
P.S:
This question might sound trivial to some of you but it is just for learning purpose and has no practical significance. FYI googling didn't help.
| One use would be in template (meta-)programming: for instance, iterator tags are implemented as empty classes. The only purpose here is to pass around information at compilation time so you can check, if an iterator passed to e.g. a template function meets specific requirements.
EXAMPLE:
This is really simplified, just... |
4,035,187 | 4,046,905 | Scanning Local Windows System for Attached USB Devices Using C++ | What is the best way to scan the local Windows system for attached USB devices using C++? I need to get a list of Vendor and Product IDs to match against the my device's IDs. If there is a way to scan for a specific VID/PID combination, that would be even better. My end goal is to retrieve the virtual COM port Windo... | I was able to resolve this by querying WMI for the needed information. Basically, I was able to start with Microsoft's example code, modify it a bit, and finally build it into my own class that does what I need.
http://msdn.microsoft.com/en-us/library/aa390423%28v=VS.85%29.aspx
This list of Computer System Hardware Cl... |
4,035,494 | 4,035,587 | Programmatically detect if Windows Media Player is installed | Anybody have any advice on how to programmatically detect if Windows Media Player is installed?
I know about the registry setting look up, but don't trust it since it's more than a little misleading (uninstalled may not remove it). And I've considered just launching a video, but an error could be caused by something o... | Look at the IsInstalled value under key HKLM\Software\Microsoft\Active Setup\Installed Components\{22d6f312-b0f6-11d0-94ab-0080c74c7e95}. It is 1 if installed, 0 otherwise.
See Detecting Windows Media Player from an Application.
|
4,035,501 | 4,043,057 | kdevelop no valid executable specified | I've just installed kdevelop 4.1 , then created a normal hello world , build is ok but when i press execute it gives me (no valid executable specified) any idea ?
| Meh, the launch configuration - our biggest usability problem...
Go to Run -> Configure Launches
select your project to the left
hit the "+" button
to the right, select your project target
optionally add a build dependency (again, select e.g. your target).
that should be it.
/me really wants to rewrite this dialog...... |
4,035,585 | 4,035,626 | Win32 MVC pattern implementation | I'm currently working on a win32 application and I'm thinking I should probably use the MVC pattern. Now according to the pattern, the code that handles user interaction should be in the controller so that I can update the model and/or view accordingly.
But in Win32, would that mean that my windowProc should be in the ... | The code that handles user interaction is view. Controller "glues" the model with the view (simply said). The window procedure definitely belongs to the GUI, i.e. the view part. From this GUI you will generate events that the controller will catch, call model and respond to them.
|
4,035,599 | 4,035,739 | How do I pass an Array (By Reference, in VB6) to a C\C++ *.dll subroutine? | I need to pass an empty Array of Variants to a DLL written in C (and available on all Windows versions), and the C code (which I have no control over and cannot edit) will populate the Empty Array of Variants with its some return values.
Bascially, when I try this - the ByRef Array is always empty when it should contai... | From http://msdn.microsoft.com/en-us/library/aa381230(VS.85).aspx:
Dim returnVal
Dim outArgs(1)
Dim args(1)
args(0) = 3
returnVal = service.InvokeAction("GetTrackInfo", args, outArgs)
'return Val now contains the track length
'and outArgs(0) contains the track title
Dim emptyArgs(0)
returnVal = service.InvokeAction("Pl... |
4,035,729 | 4,035,756 | Size of a Packed Structure of Bools | If 1 bool is 1byte [8 bits] then would a packed structure of 4 bools be 32bits or 4? The pack directive removes the alignment requirement, but would it make sets of bools more efficient [memory wise]?
| Yes. Even a packed structure of booleans will use at least 8 bits per boolean. Unless you use bit fields.
|
4,035,884 | 4,035,928 | struggling with c++ IDE's on linux | hi I'm really frustrated, First I have no idea how to code the very complex (make files), so I'm using IDE's that would ease the job for me like (netbeans , eclipse ,Kdevelop .. etc) i almost tried every thing starting with
Emacs (i'm very slow on it and I need autocompletion)
Netbeans 6.9.1 (crashes , very slow edito... | maybe you can try qt creator, it designed for developing QT application, however you can use it for other c++ program. It supports cmake.
|
4,036,108 | 4,038,334 | Defaults constructors, why my class seems to have three? When compilers treats classes like structures? | I always thought, that there are only two defaults construcors: constructor with no arguments, and copy construtor.
But today I wrote something like this:
First I wanted to make sure that in C++ initialization of structures in c-style is still valid..
struct Foo{
int a;
bool b;
char* c;
double d;
};
//.... | Although you called it C-style initialization, its official name is initializer list. Only aggregates can be initialized with initializer lists (see 8.5 in the standard).
An aggregate is an array or a class with
no user-declared constructors,
no private or protected non-static data members,
no base classes,
and no vir... |
4,036,394 | 4,036,535 | How do I call the class's destructor? | I have a simple C++ code, but I don't know how to use the destructor:
class date {
public:
int day;
date(int m)
{
day =m;
}
~date(){
cout << "I wish you have entered the year \n" << day;
}
};
int main()
{
date ob2(12);
ob2.~date();
cout << ob2.day;
return 0;
}
The qu... | You should not call your destructor explicitly.
When you create your object on the stack (like you did) all you need is:
int main()
{
date ob2(12);
// ob2.day holds 12
return 0; // ob2's destructor will get called here, after which it's memory is freed
}
When you create your object on the heap, you kinda need to... |
4,036,396 | 4,036,447 | Question about the ostream operator << | Let's say I make a class, like, which contains a char array. Now, what operator handles this:
myClass inst;
cout << inst;
At the "cout << inst;" what is called, by simply the class' name?
Thanks.
| What is called is std::ostream &operator<<(std::ostream &, myClass const &). You can overload this if you want.
|
4,036,464 | 4,036,487 | Private inheritance and swap | I'm using private inheritance in the implementation of two very related classes. The using Base::X; is very useful and elegant. However, I can't seem to find an elegant solution for reusing the base class's swap function.
class A
{
public:
iterator begin();
const_iterator begin() const;
const_iterator ... | Well, can’t you just call the base’s version of swap?
void swap( Const_A& other )
{
A::swap(other); // swaps the `A` portion of `this`.
// …
}
In place of …, you’d normally swap the members pertaining only to Const_A, not A but since there aren’t any in your particular case, this is all that you should need.
|
4,036,533 | 4,036,729 | does cvrelease delete the allocated memory? | This might be the wrong way of doing things, but I pass an array from LabView into my C++ function as a simple array of char. I then create an OpenCV image and point the pointer to my data that was passed. At the end of the function I use cvReleaseImage to delete all the OpenCV images, would that remove the data off my... | cvRelease deallocates the memory used by the image, so after calling it you can no longer reference that image.
BUT - the memory may not be available for other programs until openCV exists, it's system dependant how it handles memory, and indeed when the system returns free'ed memory for other apps.
edit: Sorry I didn'... |
4,036,715 | 4,036,791 | Timer working improperly | I have a problem with a timer class based on a SDL timer.
class CTimer
{
public:
CTimer(): startTick(0), endTick(0), curTime(0), running(false) {};
void Start() { startTick += SDL_GetTicks() - endTick; running = true; };
void Stop() { endTick = SDL_GetTicks(); running = false; };
void Reset() { star... | This is a perfect example of why you don't want to use old-style C casts in C++.
(int) SDL_GetTicks
The missing parentheses on the function call mean you're casting a pointer to the function to an int, not the return value. Surprisingly enough the pointer to the function never changes.
|
4,036,773 | 4,036,912 | Speed up compilation in Visual Studio 2005 | What are the best ways to speed up compilation time in Visual Studio 2005 for a solution containing mainly C++ projects?
| Besides pre-compiling headers, there are number of other things that could be slowing you down:
Virus checking software - can have a nasty impact on builds. If you have a virus checker running try to turn it off and see what sort of improvement you get.
Low RAM - Not enough RAM will cause many more disc reads and slow... |
4,037,219 | 4,037,283 | Order of execution in constructor initialization list | Is order of execution in constructor initialization list determinable? I know that members order in a class is the order in which those members will be initialized but if I have scenario like this:
class X()
{
X_Implementation* impl_;
};
and then providing that allocator is available:
X::X():impl_(Allocate(sizeof(X... | According to ISO/IEC 14882:2003(E) section 12.6.2:
Initialization shall proceed in the following order:
First, and only for the constructor of the most derived class as described below, virtual base classes shall
be initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic ... |
4,037,346 | 4,037,373 | map that can take any basic type inside | I need to create a map that can contain as its value any basic data type such as double,float,string, char etc... to store values from a request for a server component.
I was thinking of using a map such as this: std::map<std::string, void*>, however I don't know that this is a very good solution.
I wondered if anyone ... | You could use boost::any as the value which can hold "any" type.
(It is better to use boost::variant if there are only finitely many "basic data types")
|
4,037,474 | 4,037,493 | Is there any way to pass a std::string to a function that accepts a char* and changes its contents? | I'm trying to get back into programming, specifically console games. I'd heard that curses was good for that, so I found a curses tutorial and I'm getting into that. I'm using C++, and naturally I wanted to take advantage of std::string, but functions like getstr() only accept char*. Is there any way to pass a string a... | You can still use C++ std::string, but you'll have to copy the contents into a buffer (std::vector<char> would be good) and copy it back when using functions that expect a writable char* buffer.
|
4,037,525 | 4,045,410 | wxWidgets 2.9 custom events | I appear to have followed this example (found under "Defining Your Own Event Class"), and my code compiles and runs without error, but I'm not catching the event anywhere.
The code:
class MyCustomEvent : public wxEvent
{
//... stuff here
};
wxDEFINE_EVENT(MY_CUSTOM_EVENT_1,MyCustomEvent);
and later I bind the event:
B... | Your code looks correct so the problem is probably in the part you're not showing. Just notice that don't need to pass this as last argument to Bind() if you're calling it from a MyApp method.
I'd also advise looking at the event sample, it has working code defining a custom event (albeit using wxCommandEvent instead o... |
4,037,571 | 4,037,602 | Why is WebKit written in C++ and not in ObjectiveC | Apple is the backing force of ObjectiveC.
However WebKit is written in C++.
Apart from portability (not all systems have ObjectiveC compilers/runtimes) is there any other valid reason for this? Performance, features?
Lately Apple does not seem to care of other languages than ObjectiveC.
| Aside from portability, the use of C++ is an historical artefact. WebKit wasn't started by Apple; it was a fork of KHTML, which was developed as part of the KDE project. The decision to use C++ was made by the KHTML team, likely because KDE itself is written in C++ using the Qt framework.
|
4,037,751 | 4,037,857 | Is "program to interfaces" a common design principle in C++ projects? | I read a lot about "program to interfaces" and "inversion of control" during the last days. Mostly in the context with the Java language. My question is if it is also a common practice in C++ development. What are the advantages? What are the disadvantages?
Is it worth to apply to small projects (like 15-20 classes)?
| The principles you speak of are generally applicable to any OO language. The basic tenet here is "loose coupling". A class that depends upon another class (contains an instance of it and calls methods on it as part of its own work) really only depends on a set of functionality the dependency provides. If the class defi... |
4,037,853 | 20,571,338 | Thread-safe copy constructor/assignment operator | Let's say that we want to make class A thread-safe using an std::mutex. I am having my copy constructor and assignment operator similarly to the code below:
#include <mutex>
class A {
private:
int i;
mutable std::mutex mtx;
public:
A() : i(), mtx() { }
A(const A& other) : i(), mtx()
{
std::lock_guard<s... | Old question, new answer:
Imho, a better way to deal with the dead-lock problem of the original copy assignment operator is:
A& operator=(const A& other)
{
if (this!=&other) {
std::unique_lock<std::mutex> _mylock(mtx, std::defer_lock),
_otherlock(other.mtx, std::defer_lo... |
4,038,030 | 4,038,065 | C++ templates to make several version of function with different constant | Can I use template to create several instantiations of some function, different only in some constant parameter? The number of alternatives for this parameter is fixed.
E.g.
I want not to rewrite (where upper is in 1..32 in powers of two)
funct(param, int upper)
{
some_loops(..)
some_heavy_code_fast_for_const_... | Absolutely, this is entirely possible. If you take an int by template, it is valid wherever a constant expression is valid.
template<int const_1, int const_2> function_typical(long long double ***A, long long double ***B)
// the type "long long double" here is very correct, this is extension of compiler
{
for(int i... |
4,038,045 | 4,038,102 | C++, need help with pointers created with strcat! | I need to append a number at the end of the word flare depending on how many I have. That part works great. My problem is when I go to print it to the screen. I would like the program to output the value of what (Camera::Table[Id]->sensor->flare1) sensor is pointing at, in this case, flare one. If the program were to c... | You can't access a variable like that in C/C++. You have to redesign the "sensor" structure to contain an array instead of individual flares, and access the array by index: Camera::Table[Id]->sensor->flare[1], Camera::Table[Id]->sensor->flare[2], etc.
|
4,038,088 | 4,064,804 | URLOpenPullStream and gzip content download - need uncompressed data | I am using URLOpenPullStream along with a IBindStatusCallback and IHttpNegotiate callbacks to handle the negotiate, status, and data messages. Problem that I have is when the content is gzip (e.g. Content-Encoding: gzip). The data that I am receiving via OnDataAvailable is compressed. I need the uncompressed data.... | I will answer my own question after more research. It seems that the website that I having the issue with is returning something incorrect where IE, FF, and URLOpenPullStream do not recognize it as valid gzip content. The headers appear to be fine, e.g.
HTTP/1.1 200 OK
Content-Type: text/html; charset=iso-8859-... |
4,038,095 | 4,038,757 | Javascript code working in the html file not working when taken as a string in C++ | I have html file with javascript code the contents of the file are as under:
I tried this code on Safari and it was working fine. But when I tried this on Firefox, it’s not working. Can any one suggest how to make it working on firefox.
<html><head></head><body><button type="button" onClick="handleButtonClick();">und... | First of all if you are going to create an XMLHttp object for requesting the server in different browsers be sure it is valid in the browser you are using (different browser have different manner to refer the XMLHttp object), normally this object is created as follow:
function getRequestObject(){
var xmlHttp;
i... |
4,038,232 | 4,038,254 | how to template for operator<< for ostream | The following won't compile for me. I'm out of ideas... Any help?
template<>
inline
std::ostream& operator<< <const std::map<std::string, std::string> > (std::ostream& stream, const std::map<std::string, std::string>& some_map)
{
return stream;
}
g++ gives me the following error:
error: expected initializer before '... | This doesn't need to be a template function.
std::ostream & operator<<(std::ostream & stream, const std::map<std::string, std::string> & some_map)
{
return stream;
}
Edit:
In reference to my comment about writing Java in C++(and sorry if it sounded rude, I didn't intend to be smarmy). Tell me if this doesn't work... |
4,038,256 | 4,038,376 | "Interface" like semantics with boost::bind | I wanted to be able to have something like Java's interface semantics with C++. At first, I had used boost::signal to callback explicitly registered member functions for a given event. This worked really well.
But then I decided that some pools of function callbacks were related and it made sense to abstract them a... | boost::bind takes its parameters by value and copies them. That means
f = boost::bind<void>(boost::mem_fn(&X::go), x);
will pass a copy of x, which will slice off the Y piece of it (if it was really a Y to begin with). To get virtual dispatch to work, you need to pass a pointer to boost::bind:
f = boost::bind(&X::go, ... |
4,038,302 | 4,038,308 | How do I make a C++ console program exit? | Is there a line of code that will terminate the program?
Something like python's sys.exit()?
| #include <cstdlib>
...
exit( exit_code );
|
4,038,377 | 4,038,434 | Superscript in C++ console output | I'd like to have my program output "cm2" (cm squared).
How do make a superscript 2?
| As Zan said, it depends what character encoding your standard output supports. If it supports Unicode , you can use the encoding for ²(U+00B2). If it supports the same Unicode encoding for source files and standard output, you can just embed it in the file. For example, my GNU/Linux system uses UTF-8 for both, so th... |
4,038,708 | 4,038,725 | Questions about const and ifdef |
Possible Duplicates:
the role of #ifdef and #ifndef
How many and which are the uses of “const” in C++?
I am new to this field and I am just not getting certain functions or concepts.
For example, I have this code:
#ifdef directory
Now, we could use a simple if condition in the program. So why is #ifdef used? I do... | I can help you on your first point. The use of #ifdef is to change what code is compiled based on previously configured information.
For example:
#define MAKE_SEVEN
#ifdef MAKE_SEVEN
int x = 7;
#else
int x = 9;
#endif
is _exactly the same as:
int x = 7;
as far as the compiler is concerned.
Why is this use... |
4,038,756 | 4,038,785 | DevCPP / VS windows app header problem (noob) | I'm working through theForger's win32 tutorial, on two IDEs: Dev C++ and Visual Studio 2008. I try to duplicate results in both.
For this page of the tutorial, I can't seem to compile in Dev C++ (Visual Studio works fine). It's a modal dialog box. The code in question is in WndProc:
case ID_HELP_ABOUT:
int ret = D... | Some compilers expect curly braces to be added between Case statement and break. Try using it.
I think it should work that way.
Besides regarding <> and "" for declaring headers, angular brackets indicate that the file will be searched in the default include directories mentioned with IDE. Whereas the "" are used when ... |
4,039,025 | 4,039,068 | using a simple assert() macro | I'm new to programming & i found this code when i was going through a book. I believe it gives an example of how to use a defined assert() macro. It doesn't compile on code::blocks 10.05. I get errors such as
'#' is not followed by a macro parameter
unterminated #else
in function 'int main()' 'ASSERT' was not declared... | if(!(x))\
{\
cout<<"Error!!Assert"<<#x<<"failed\n";\
cout<<"on line"<<__LINE__<<"\n";\
cout<<"in file"<<__FILE__<<"\n";\
} // no backslash
|
4,039,229 | 4,041,286 | Checking if two cubic Bézier curves intersect | For a personal project, I'd need to find out if two cubic Bézier curves intersect. I don't need to know where: I just need to know if they do. However, I'd need to do it fast.
I've been scavenging the place and I found several resources. Mostly, there's this question here that had a promising answer.
So after I figured... | Intersection of Bezier curves is done by the (very cool) Asymptote vector graphics language: look for intersect() here.
Although they don't explain the algorithm they actually use there, except to say that it's from p. 137 of "The Metafont Book", it appears that the key to it is two important properties of Bezier curve... |
4,039,378 | 4,040,834 | x86 MUL Instruction from VS 2008/2010 | Will modern (2008/2010) incantations of Visual Studio or Visual C++ Express produce x86 MUL instructions (unsigned multiply) in the compiled code? I cannot seem to find or contrive an example where they appear in compiled code, even when using unsigned types.
If VS does not compile using MUL, is there a rationale why?... | imul (signed) and mul (unsigned) both have a one-operand form that does edx:eax = eax * src. i.e. a 32x32b => 64b full multiply (or 64x64b => 128b).
186 added an imul dest(reg), src(reg/mem), immediate form, and 386 added an imul r32, r/m32 form, both of which which only compute the lower half of the result. (Accordi... |
4,039,817 | 4,039,892 | friend declaration declares a non-template function | I have a base Class akin to the code below. I'm attempting to overload << to use with cout.
However, g++ is saying:
base.h:24: warning: friend declaration ‘std::ostream& operator<<(std::ostream&, Base<T>*)’ declares a non-template function
base.h:24: warning: (if this is not what you intended, make sure the function t... | It sounds like you want to change:
friend ostream& operator << (ostream& out, const Base<T>& e);
To:
template<class T>
friend ostream& operator << (ostream& out, const Base<T>& e);
|
4,039,850 | 4,040,084 | How can I substring a TCHAR | I have a TCHAR and value as below:
TCHAR szDestPathRoot[MAX_PATH]="String This";
Now I want the 1st three character from TCHAR , like below:
szDestPathRoot.substring(0,2);
How can I do this.
| TCHAR[] is a simple null-terminated array (rather than a C++ class). As a result, there's no ".substring()" method.
TCHAR[] (by definition) can either be a wide character string (Unicode) or a simple char string (ASCII). This means there are wcs and str equivalents for each string function (wcslen() vs strlen(), etc e... |
4,039,868 | 4,039,887 | Prepending a string to a logger on function entrance | I have a logger class. Call it MyLogger. I may use it in a function like this:
void MyFunc(MyLogger& oLogger)
{
//Do stuff
oLogger.Log("In MyFunc : Some Error");
//Do something else
oLogger.Log("In MyFunc : Some other error");
}
Now, I want to prepend "In MyFunc" to the logs if the log comes from inside My... | RAII - Resource Acquisition Is Initialization.
In this case, you create an object on entry to the function that identifies the current function to the logging system; when the function exits (by any return or by exception thrown or by exception not caught), the object will be destroyed, and the destructor changes what ... |
4,039,979 | 4,040,833 | Some compiler errors concerning an overloaded operator on a template in c++ | I have some code with a few errorr I do not understand how to fix at all. I have asked my professor and TA, and consulted the internet with no luck, apart from understanding more precisely what the errors mean. From what I can tell, the compiler is either confusing my overloaded operator with built in operators, or i... | The second error is in this line:
Forest < char > intForest();
This may be surprising at first, but that line is not declaring a variable of type Forest<char>, but rather a function that takes no arguments and returns a Forest<char>.
Just remove the parenthesis from the declaration:
Forest < char > intForest;
On the... |
4,040,264 | 4,040,310 | Integrating wxwidgets in visual studio 2008 | I want to make window-base application in c++, I have listen about wxwidgets.
Can any one tell me how can I use wxwidgets library in my application, any link or tutorial which give me direction.
| This is a gentle introduction to wxWidgets in a Microsoft environment. Browse the other stackoverflow questions tagged with wxwidgets too.
|
4,040,403 | 4,040,454 | How to find out if this preprocessor macro exists? | I want to know how to find out if the preprocessor macro __PRETTY_FUNCTION__ can be used with a given compiler (As it is supposed to be non-standard). How do I check this in a header file? What I want to do is something like:
#ifndef __PRETTY_FUNCTION__
#define __PRETTY_FUNCTION__ __func__
#endif
But, I'm guessing ... | You probably have to know which compiler you're using. For GCC (the GNU Compiler Collection), you'd probably test:
#ifdef __GNUG__
...use __PRETTY_FUNCTION__
#endif
You might check the compiler version if you know which one introduced the feature and you are in any danger of having your code compiled with an older ve... |
4,040,840 | 4,040,897 | #if inside the function | anybody can explain me epsilon what is this term although i did not use in my header file.
like
Right (const lPoint& a, const lPoint& b, const lPoint& c, double epsilon)
{
#if _NOT_USED_EPSILON
return (( (a.x_ * b.y_) - (a.y_ * b.x_) +
(a.y_ * c.x_) - (a.x_ * c.y_) +
(b.x_ * c.y_) - (c... | This code is simple. What it does is this?
If the preprocessor symbol _NOT_USED_EPSILON is defined (through make file, command line) etc, then the expression is checked if it is less than 0.
In some cases (since double arithmetic looses precision), one may check the value of the expression if it is significantly close ... |
4,041,000 | 4,041,093 | What is this error? (And why doesn't it occur in other classes?) | I'm trying to write a some container classes for implementing primary data structures in C++. The header file is here:
#ifndef LINKEDLIST1_H_
#define LINKEDLIST1_H_
#include <iostream>
using namespace std;
template<class T> class LinkedList1;
template<class T> class Node;
template<class T>
class Node
{
friend cl... | See FAQ item 35.12 "Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?".
Most probably that's what you're running into.
Cheers & hth.,
|
4,041,003 | 4,041,116 | c++ What process is listening on a certain port in windows | I have created a program in visual c++, where i have implemented a web service.
The web service is set to listen on port 80, but if another program already is using this port, the web service fail to start up.
So when the webservice can't start, I would like to have a function or method, which can get the name of the ... | GetExtendedTcpTable and GetExtendedUdpTable give you a list of network connections. You can walk through this list and check if a program is using port 80 (it provides process IDs as well).
|
4,041,015 | 4,041,107 | Using C++ and scripting together | I am developing simple games as a hobby. For my new project, I want some parts to be scriptable. I am familiar with python but don't mind learning new languages. Here is the question:
I am planning to implement path-finding, field-of-vision, collision detection etc. in C++ but want to use scripts for AI state machines,... | From my personal experience, both lua and tcl have fantastic C APIs for embedding. Both languages are very simple. If you're writing a command interface, I'd probably say go with tcl, but if you're just using an embedded interpreter, I'd recommend lua. Given that you're using C++, you might also want to look into the l... |
4,041,308 | 4,041,625 | C++ console game input && refresh function | I am writing a small console adventure game and I faced a few problems.
1. The input is kinda laggy, I'm using while loop ( while(getch() == 'w') ). After a key is pressed the first time, nothing happens (you have to press it 2 times) and if you switch directions (press key A/D/S) it also doesn't react the 1st time. If... | Don't use system("cls"), it is really slow, instead set the cursor on the beginning of the screen with the following code:
COORD cur = {0, 0};
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cur);
You should call getch() only one time in the loop, like this:
char key;
do
{
key = getch();
if(key == ... |
4,041,447 | 10,869,923 | How is std::tuple implemented? | I'd like to know how are tuple implemented in standard library for C++0x. I tried to read description in libstdc++ manual and then read template listing, but it's really hard to understand how it works, especially when reading code.
Can someone explain me in few sentences the idea of tuple implementation? I want to kno... | One approach to implementing tuples is using multiple-inheritance. The tuple-elements are held by leaf-classes, and the tuple class itself inherits from multiple leafs. In pseudo-code:
template<typename T0, typename T1, ..., typename Tn>
class PseudoTuple : TupleLeaf<0, T0>, TupleLeaf<1, T1>, ..., TupleLeaf<n, Tn> {
... |
4,041,726 | 4,085,856 | How does the OS language represented in Linux | My Application is running in Linux.
it would be localized.
how can I get the OS Language?
is it represented in Linux?
as a numeric values?
| Since most of your other questions relate to Qt, you might want to read the documentation of the static function QLocale::system()
|
4,041,799 | 4,049,087 | c++ fstream concurrent access | What will happen if files are accessed concurrently from different processes/threads?
I understand there is no standard way of locking a file, only os specific functions.
In my case files will be read often and written seldom.
Now if A open a file for reading (ifstream) and starts reading chunks. And B opens the same f... | There is certainly no portable way to do efficient file sharing (with simultaneous access) using C++.
You can share files using a "lock" file. Before opening "foo.dat", try to create file "foo.lock". Keep looping until you succeed. After access, delete foo.lock. That allows serial access, but not concurrent acce... |
4,042,095 | 4,042,266 | A puzzle for template wizards | I'd like to do the following:
const int someInt;
const std::vector<int> someIntList;
const std::vector<std::vector<int>> someNestedIntList;
Marshall(someInt); // trivial case
Marshall(someIntList); // difficult case
Marshall(someNestedIntList); // difficult case
I tried the following:
template<std::vector<class Eleme... | May I propose SFINAE and some boost metaprogramming?
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>
template <class T>
struct has_begin_end
{
template <class U,
typename U::const_iterator (U::*)() const,
typename U::const_iterator (U::*)() const>
struct sfin... |
4,042,197 | 4,042,235 | what makes const at the lower levels of the machine? | When making something const in C++ what makes it that you cannot for example implicitly pass it a non-const at the lower levels of the machine? How is it determined by the machine that this is const?
(besides the fact that const means what it means...)
Is it perhaps stored in the .rdata section of memory or is there a... | const is mostly a compile-time thing; it doesn't imply anything about where they might be stored at runtime, or whether they might be protected at runtime.
In practice, the compiler may choose to put constants in the program section of the executable, which may be write-protected by the memory-management unit (if it ex... |
4,042,212 | 4,042,528 | Obtain a list of partitions on Windows | Goal
I'm porting a filesystem to Windows, and am writing a more Windows-like interface for the mounter executable. Part of this process is letting the user locate a partition and pick a drive letter. Ultimately the choice of partition has to result in something I can open using CreateFile(), open(), fopen() or similar.... | As you noted, you can use IOCTL_DISK_GET_DRIVE_LAYOUT_EX to get a list of partitions.
There's a good overview of the related concepts here. I wonder if the missing link for you is
Detecting the Type of Disk
There is no specific function to
programmatically detect the type of
disk a particular file or directory is... |
4,042,629 | 4,042,637 | Affectations and exceptions | Lets consider I have the following function:
SomeType createSomeType();
which can throw depending on some reasons.
Then:
SomeType val = SomeType(); // initial value
try
{
val = createSomeType(); // here
}
catch (std::exception&)
{
}
If createSomeType() throws, can I always assume that val value is unchanged ?
| Yes, if createSomeType() throws an exception, the assignment will not happen. The flow of control will go from the throw statement, through the destructors of any objects createSomeType() has on the stack and finally to the catch statement.
|
4,042,711 | 4,042,782 | How to resize an image in C++? | I have an image which is representative of an Array2D:
template<class T = uint8_t>
Array2D<T> mPixData[4]; ///< 3 component channels + alpha channel.
The comment is in the library. I have no clues about the explanation.
Would someone:
explain what are the 3 component channels + alpha channel are about
show how I cou... | Without know what library this is, here is a stab in the dark:
The type definition implies that it is creating a 2D array of unsigned chars (allowing you to store values up to 255.
template<class T = uint8_t> Array2D<T>
Then, mPixData itself is an array, which implies that at each co-ordinate, you have four values (by... |
4,042,829 | 4,056,920 | wxDialog with the wxMenuBar | I have tons of existing code using wxWidgets. The main window is wxDialog. Now I have to add a wxMenuBar to that dialog. But, in order to do it, the window should be derived from wxFrame.
Is it possible to add a wxMenuBar to the wxDialog?
If not, is it possible to convert existing code in a way that main window is deri... | It's not possible to add a native menu bar to a wxDialog, however, it is possible to use a non-native menu bar control like wxFlatMenuBar (not included with wxWidgets), and add it to the top of the dialog as if it was just another control. Also note though that besides being a non-native menu bar, you also won't be abl... |
4,042,955 | 4,077,534 | LabView: How to pass in parameters to .NET method using "Invoke Method" vi? | I have a .NET class library that I wrote in C++. "public ref class MyClass" defines a method "MyMethod" that takes two System::Int32 parameters.
Here is MyClass first then my question:
namespace MyNetAssembly {
public ref class MyClassThatDoesStuff
{
public:
MyClassThatDoesStuff();
voi... | I think I figured it out! Apparently, there is something funny happens within the vi file itself. If there is a .NET Constructor Node with an assembly defined, then rebuilding the assembly in Visual Studio and updating the Constructor Node does not have an effect over imported method signatures. Therefore, MyMethod(Sys... |
4,042,974 | 4,043,113 | Optional method arguments in C++, but from the callee's side? | In C++ methods can have optional arguments, like this:
void myFunction (int arg1, int arg2=0);
In this case myFunction can be called with 1 integer or with two. If you omit the second integer, the value 0 is passed instead.
I am now looking for ways to obtain the same functionality, but from the callee's side. Suppo... | In this case, I would consider abstract concept of additional parameters, since they are for only some specific implementations. Your interface will become like:
class IObserver
{
public:
virtual bool operator() (OtherClass *instance, IObserverArgs* args) = 0;
};
And implementation need additional a... |
4,043,121 | 4,043,213 | Why am I getting zero? | In this code (ready to compile):
#include "stdafx.h"
#include <iostream>
#include <sstream>
using std::cout;
template<class T, int first, int second>
T make()
{
T result = T();
std::stringstream interpreter;
interpreter << fir... | This works for me with two tweaks, remove the redundant typename decelerations:
template<int first, int second>
typename Real<first,second>::type typename Real<first,second>::value = typename Make<first,second>::value;
becomes:
template<int first, int second>
typename Real<first,second>::type Real<first,second>::val... |
4,043,187 | 4,043,239 | In C++, can I represent a class type as a variable? | I would like to call a static method from a class that I'll determine at run-time, but which I know subclasses a given class. So let's say I have these classes
class super {
public:
super();
static super *loadMe (ifstream &is);
}
class subA : public super {
public:
subA();
static super *loadMe (i... | You might want to look at the Factory Pattern. If you are designing a plugin architecture you can simple have a function that returns a pointer to the desired factory. Polymorphism can then do the rest for you.
|
4,043,385 | 4,044,068 | Error: the global scope has no GetUrl | I have a new problem with my C++ DLL... I have tried exporting the entire class instead of only one method. But the program doesn't want to compile now because of that the global scope has no GetUrl
Here is my "UrlConnector.h":
#define ConnectMe __declspec( dllexport )
namespace ConnectHttps
{
class ConnectMe
{
v... | Unless I'm mistaken, you don't seem to be giving your class a name.
You made ConnectMe not a class name but a macro to export your class, but your class should have a name
Maybe try
#define EXPORT_IT __declspec( dllexport )
namespace ConnectHttps
{
class EXPORT_IT ConnectMe
{
void GetUrl(char *url, un... |
4,043,574 | 4,045,204 | Manage falling using rays in Irrlicht | In my game i'm currently working on, i only need very basic physics, so i don't want Newton, ODE, Bullet or similar. I basically only want to fall as long as no node (all equally sized blocks) is beneath me. I tried to send a ray from the camera and 100.0 units downwards. But it gives false positives.
selectedNode = NU... | irrlicht has source code available. I would try tracing into the code in debug mode and see what it's doing.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.