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 |
|---|---|---|---|---|
7,530,784 | 7,530,835 | Something unclear with operator delete | I am new to C++ and I have something unclear:
#include <iostream>
using namespace std;
double* foo(void)
{
double* b = new double[100];
return b;
}
int main()
{
double* a = foo();
delete [] a;
return 0;
}
Is there something wrong with this code? I mean whether the way I use operator delete is ri... | The code is correct (though not usually part of any well-written modern C++ program).
Dynamically allocated arrays are stored with hidden information about their size so that delete[] p knows how many elements to delete.
If you're curious about the details, you can rig up a little test class and take advantage of the ... |
7,530,943 | 7,531,037 | When and who to detach observers when the observer has longer life span than the observable | I encountered this problem using a third party library provided by a different group in the company (written in C++).
In the destructor of Observer, it detaches itself from all observables it subscribes to, this part makes sense to me. But in the destructor of Observable, it checks if the observable has any observer th... | If the Observer has a pointer (or reference) to the Observable, and the Observable is destroyed, that pointer will be invalid. The author is just trying to avoid dangling references.
There are three usual solutions, I think.
One is to do exactly what this code does, perhaps calling abort() rather than throwing an exce... |
7,531,039 | 7,809,357 | libmagick equivalent of TIFFReadRGBAImage | High.
I was trying to find a well written API documentation for libmagick[++] to get a raster memory block for RGB[A] image data. Something equivalent to this guide or at least well documented classes, methods and properties.
Can anyone point me in the right direction?
Thanks.
Edit:solved:
void Magick::Image::write(Blo... | void Magick::Image::write(Blob *blob_,
const std::string &magick_,
const unsigned int depth_);
|
7,531,051 | 7,531,311 | C++ Win32 Radio button background color | So first i'm using the windows API, no special libraries.
I've created a radio button with this code:
g_hRadioButton = CreateWindowEx(0, "BUTTON", "Radio Button",
WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON,
10, 55, 120, 25, hWnd, (HMENU)RADIOBUTTON, GetModuleHandle(NULL), NULL);
Now I have a black background for t... | Perhaps as soon as your application is running with visual styles, you will be better off handling NM_CUSTOMDRAW notification for button control. Originally, these were for common controls only, but quite a few versions are already extending button behavior the same way too.
|
7,531,113 | 7,531,171 | Monitoring open programs with Win32 | I've searched the web, and various forums, but I can't find one thing, how to continually monitor open programs and then close another program (not the one being monitored) if something happens to the program being monitored.
For example, say that there is an already open Notepad window, and then the user or some other... | On windows, you can use PSAPI (The Process Status API) to know when processes are started and terminate. The EnumProcesses function can give you this information.
A more reliable method to determine that a process terminated (since process ids can be reused) is to wait on its process handle (you will need the SYNCHRONI... |
7,531,136 | 7,533,599 | dylib destructor does not get called | I have a dylib which I can load via injection on mac os x.
Constructor call works well.
__attribute__((constructor))
static void initialize()
But destructor does not get called? Thus resources initialized leaks.
__attribute__((destructor))
static void destroy()
Does dylib gets unloaded automatically if application... | 1, 2: No. Libraries aren't really unloaded when an application exits -- they just happen to disappear along with the rest of the process, in the same way that other resources (e.g, file handles, mapped memory, sockets, etc) are released on exit.
3: Depends on how you injected the library. If you loaded it using somethi... |
7,531,396 | 7,531,606 | iOS - GCC failing to see a function that seems to be plainly visible | This problem may be as a direct result of either me misunderstanding the limitations of Objective-C(++) and how it interacts with C++. Or it may be a case of me missing something thats right in front of me.
I have a C++ class that does some Objective-C++ work behind the scenes. As such I have a templated C++ class th... | This is classical name lookup problem. The compiler stops looking for names when it finds a function with the same name, ignoring the signature. Only then it checks the signature and finds it does not match.
You want to call the free version, so you need to say:
return ::MakeUIImage( BaseImage< ColourSpace >::Pixels()... |
7,531,556 | 7,531,619 | How to cast a LONG to a CString? | I want to cast a long to a cstring.
I've been struggling with this for a while and I've seen so many variants of solving this problem, more or less riddled with hassle and angst.
I know the question seems subjective, but it really shouldn't be in my opinion. There must be a way considered to be the best when the circum... | It's as simple as:
long myLong=0;
CString s;
// Your one line solution is below
s.Format("%ld",myLong);
|
7,531,608 | 7,531,841 | What is an alternative set-like data structure when modifying elements is necessary? | STL sets are designed so that it is not possible to modify the elements in the set (with good reason, see stackoverflow). Suppose however I have a structure in which only one of the members acts as the key. Is there an alternative data structure to a set. I really want exactly the behavior of sets except this inabil... | May be it's time to redesign, considering std::map instead of std::set.
instead of
struct A
{
K key;
V val;
};
set<A> a;
consider
std::map<K,V> m;
you can then do
m[k] = v;
|
7,531,675 | 7,531,676 | Why is the constructor for my class not being called in this case? | I am creating a new class instance like this:
Cube* cube1;
There is code in the Cube constructor, but it's not being run! Is this usual?
| You're actually not creating any instance.
the variable you're calling cube1 is a pointer to a Cube.
To create a Cube you should have:
Cube* cube1 = new Cube();
This create a new instance of Cube in heap memory, you should call delete cube1 once you don't use it anymore.
or:
Cube cube1;
This create a new instance of ... |
7,531,692 | 7,533,696 | LLVM exceptions; how to unwind | at the moment, i'm inserting variables into the beginning of block scope using CreateEntryBlockAlloca:
template <typename VariableType>
static inline llvm::AllocaInst *CreateEntryBlockAlloca(BuilderParameter& buildParameters,
const std::string &VarName) {
HAssertMsg( 1 !=... |
The thing i don't know is how to query the offset of the Alloca'ed registers created with CreateAlloca. How can i do that reliably?
You can use the address of an alloca directly... there isn't any simple way to get its offset into the stack frame, though.
Why exactly do you not want to use the intrinsic LLVM exceptio... |
7,531,729 | 7,531,747 | Very Basic std::vector iterating | std::vector<Ogre::SceneNode*>::iterator itr;
for(itr=mSelectedObjects.begin();itr!=mSelectedObjects.end();itr++){
itr->showBoundingBox(true); //here
}
I'm getting "expression must have pointer-to-class type" on the marked line, and I'm not sure why. Can anyone help?
| Replace the erroneous line with:
(*itr)->showBoundingBox(true); //here
Since you're storing pointers, you need to dereference itr twice to get from the iterator to the object (once for the iterator and once for the pointer).
|
7,531,783 | 7,531,937 | RValue references, pointers, and copy constructors | Consider the following piece of code:
int three() {
return 3;
}
template <typename T>
class Foo {
private:
T* ptr;
public:
void bar(T& t) { ptr = new T(t); }
void bar(const T& t) { ptr = new T(t); }
void bar(T&& t) { (*ptr) = t; } // <--- Unsafe!
};
int main() {
Foo<int> foo;
int a = 3;
... | In this line
void bar(T&& t) { (*ptr) = t; } // <--- Unsafe!
you can dereference an uninitialized pointer. This is undefined behavior.
You must call one of the two other version of bar first because you need to create the memory for your object.
So I would do ptr = new T(std::move(t));.
If your type T supports moving ... |
7,531,866 | 7,531,885 | "Unresolved overloaded function type" while trying to use for_each with iterators and function in C++ | //for( unsigned int i=0; i < c.size(); i++ ) tolower( c[i] );
for_each( c.begin(), c.end(), tolower );
I am trying to use a for_each loop in place of the for loop for an assignment.
I am unsure why I am getting this error message:
In function âvoid clean_entry(const std::string&, std::string&)â:
prog4.cc:62:40: error:... | Write:
for_each( c.begin(), c.end(), ::tolower );
Or :
for_each( c.begin(), c.end(), (int(*)(int))tolower);
I've faced this problem so many times that I'm tired of fixing this in my code, as well as in others' code.
Reason why your code is not working : there is another overloaded function tolower in the namespace ... |
7,531,878 | 7,532,279 | Boost.Assign: using objects with map_list_of? | Using C++ with boost. In Boost.Assign can I use the new operator with map_list_of?
For example:
std::map<int, MyObject*> objects = boost::assign::map_list_of
(1, new MyObject())(2, new MyObject())(3, new MyObject())
If not, is there another way to do it?
| Seems yes. This compiles fine with VS2010 & boost 1.47.
#include <boost\assign.hpp>
class MyObject{
public:
MyObject(int i):m_i(i){}
private:
int m_i;
};
int main (void)
{
std::map<int, MyObject*> objects = boost::assign::map_list_of(1, new MyObject(1))(2, new MyObject(2))(3, new MyObject(3));
}
|
7,531,882 | 7,532,003 | What is the fastest way to find a file in a directory tree | I have a directory tree similar to the one below. It contains around 30,000 files in total.
rootDir
rootDir\subDir1
rootDir\subDir1\subSubDir1
rootDir\subDir1\subSubDir2
rootDir\subDir2
rootDir\subDir2\subSubDir1
rootDir\subDir3
...
rootDir\subDirN
What is the fastest way to find a file from a directory structure such... | If you do have Windows Desktop Search or Windows Search operating (or the target computer might have it, anyway), you can use ISearchFolderItemFactory (or ISearchDesktop, for WDS) to have it do a search for you.
If there's no pre-existing index, nearly the only way to do this is with FirstFirstFile, FindnextFile and Fi... |
7,531,890 | 7,531,944 | function of searching a string from a file | This is some code I wrote to check a string's presence in a file:
bool aviasm::in1(string s)
{
ifstream in("optab1.txt",ios::in);//opening the optab
//cout<<"entered in1 func"<<endl;
char c;
string x,y;
while((c=in.get())!=EOF)
{
in.putback(c);
in>>x;
in>>y;
if(x==s)
return true;
}
return false;
}
... | What a hack! Why not use standard C++ string and file reading functions:
bool find_in_file(const std::string & needle)
{
std::ifstream in("optab1.txt");
std::string line;
while (std::getline(in, line)) // remember this idiom!!
{
// if (line.substr(0, needle.length()) == needle) // not so efficient
if... |
7,531,912 | 7,532,264 | CURL and ZLIB Compilation | When compiled correctly, how are these two associated together? I'm attempting to use the ZLIB library in my CURL install and want to confirm that I've compiled CURL and ZLIB correctly. Should the libcurl.lib now have all of ZLIB after a successful compile or is the zlib.lib library still required?
| The .lib archives are just a collection of compiled source files, nothing more. By convention and practicality, they only include the objects compiled for their respective library. So, to link against the libcurl you have created, you must also link against the zlib. Professional configuration systems (e.g. pkg-config)... |
7,531,933 | 7,532,870 | CreateFileMapping for Directory | I have this function which gives the full file name(path) from the file handle. The only problem is CreateFileMapping fails for directory handles. Is there a workaround for it?
I get the handle using NtCreateFile()
ULONG status = NtCreatefile(&f, GENERIC_ALL, &oa, iosb, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ ... | You can use NtQueryInformationFile with FileNameInformation to retrieve the name associated with a file handle.
|
7,531,981 | 7,532,016 | How to instantiate a static vector of object? | I have a class A, which has a static vector of objects. The objects are of class B
class A {
public:
static void InstantiateVector();
private:
static vector<B> vector_of_B;
}
In function InstantiateVector()
for (i=0; i < 5; i++) {
B b = B();
vector<B>.push_back(b);
}
But I have compilation error using... | You have to provide the definition of vector_of_b as follows:
// A.h
class A {
public:
static void InstantiateVector();
private:
static vector<B> vector_of_B;
};
// A.cpp
// defining it fixes the unresolved external:
vector<B> A::vector_of_B;
As a side note, your InstantiateVector() makes a lot of unneces... |
7,532,049 | 7,532,722 | Strategy for dealing with floating point inaccuracy | Is there a general best practice strategy for dealing with floating point inaccuracy?
The project that I'm working on tried to solve them by wrapping everything in a Unit class which holds the floating point value and overloads the operators. Numbers are considered equal if they "close enough," comparisons like > or < ... | You want to keep data as dumb as possible, generally. Behavior and the data are two concerns that should be kept separate.
The best way is to not have unit classes at all, in my opinion. If you have to have them, then avoid overloading operators unless it has to work one way all the time. Usually it doesn't, even if... |
7,532,278 | 7,532,510 | c++ win32 efficient context menus and submenus | I would like to add a right click context menu/sub menus to my win32 application (c++) when the user right clicks on the notifiyicon data (tray icon). I can make a simple 1 level menu, but can't find a example for multiple level menus.
I would like to a create a menu which looks something like this:
Settings -> Settin... | A submenu is just another HMENU (From CreatePopupMenu()) inserted as a menu item with AppendMenu/InsertMenu using the MF_POPUP flag or with InsertMenuItem with MIIM_SUBMENU in the mask.
There is nothing stopping you from creating the menu when your application starts but unless the menu has a large amount of items or c... |
7,532,529 | 7,532,551 | Return of memory at the termination of a C++ program | When a C++ program terminates, the RAM used during the run gets cleaned and is returned to the system, correct?
Question 1)
Is this memory returned managed by C++ language features or by the computer hardware itself?
Question 2)
Does the memory get returned efficiently/safely, if I terminate a run using ctrl+Z in Unix... |
When a C++ program terminates, the RAM used during the run gets cleaned and is returned to the system, correct?
Correct. By System, I hope you mean, Operating System.
Question 1) Is this memory returned managed by C++ language features or by the computer hardware itself?
The returned memory is managed by the operat... |
7,532,737 | 7,532,813 | OpenGL rotating textured planes in 3D space | I'm wondering if anyone could point me to any resources that would deal in rotating one or several 2D textured planes in 3D space. Something like this but with openGL (preferably C++):
I'm attempting to do pretty much the exact same thing but no matter how I order my operations I'm getting right-screwy results. So I f... | If you havent already, do a search for 'NeHe tutorials'. An excellent set of OpenGL tutorials.
Here is a link to the rotation tutorial, includes all the source code in downloadable format and the tutorial walks you through each relevant line.
http://nehe.gamedev.net/tutorial/rotation/14001/
I believe this is working i... |
7,532,970 | 7,535,582 | Lib usb how to read character from port | I want to write an application that reads data from the USB device and was looking for a library that can make the job easier. I found a library called lib-usb. Unfortunately, it has almost no documentation. Here is what I have tried:
#include <stdio.h>
#include <stdlib.h>
#include <usb.h>
int main(){
str... | USB doesn't really transfer characters -- it transfers packets. Additionally, your code makes no sense at all; there is some pretty good documentation online at http://libusb.sourceforge.net/api-1.0/, which I recommend that you read.
|
7,533,321 | 7,533,380 | Error when compiling some simple c++ code | I try to compile this cpp code on osx lion but I get an error.
#include <iostream>
using namespace std;
int main (int argc, char *argv[])
{
for(int i = 0; i < 10; i++)
{
cout << "hi";
cout << endl;
}
return 0;
}
To compile:
cc main.cpp
Error:
Undefined symbols for architec... | Normally this sort of failure happens when compiling your C++ code by invoking the C front-end. The gcc you execute understands and compiles the file as C++, but doesn't link it with the C++ libraries. Example:
$ gcc example.cpp
Undefined symbols for architecture x86_64:
"std::cout", referenced from:
_main i... |
7,533,583 | 7,535,276 | Designing an event-driven head-tracking library in C++ | I want to provide my team with a very simple C++ interface to OpenCV head tracking.
What architecture is best for this application?
Should I provide an "event-driven" API or should I make the client query this library whenever it wants a head position (yuck)?
Should I ask the client application to define callback func... | I will follow the delegation pattern used in the TUIO C++ interface. http://www.tuio.org/?cpp
MyHeadTrackerListener listener; // defines a listener
HeadTrackerClient client; // creates the client
client.addHeadTrackerListener(&listener); // registers the listener
client.connect(); // starts the client
As it says in ... |
7,533,636 | 7,535,052 | Manage timeouts for multiple UDP sockets | I have to write a TFTP (Trivial File Transfer Protocol) server on Windows and Linux for a university course. I'm using C++ and I want to use one thread and select() to check for new incoming packets. TFTP requires that if a packet is not acknowledged for a certain amount of time, that the packet is re-sent. I'm wonderi... | If I understand it correctly, you have pairs of connection/timeout, and you want to be able to access those pairs by connection as well as by timeout.
By connection because you have to change the timeout when you receive a packet, and by timeout because you need to know what is the next connection to timeout.
If you ha... |
7,533,703 | 7,881,218 | How to use Botan Amalgamation files and VS2008 |
Clean install of Windows XP SP3
Install Python 2.7.2
Extract Botan 1.10.1 to the desktop
Run configure.py --cc=msvc --disable-shared --gen-amalgamation
Copy botan_all.h and botan_all.cpp to my dev workstation
Make a new project Win32 console project in VS2008
This gives me 102 errors ... anyone using this library?
... | The problem is your project is a windows application and includes windows.h, windows.h includes macros for min and max.
The solution is to define #define NOMINMAX
You can do through the project's property pages > C/C++ > Preprocessor > Preprocessor definitions
Also, add #define BOTAN_DLL in botan_all.h to avoid error... |
7,533,792 | 7,533,864 | How do you enumerate all accelerators in C++ AMP? | In C++ AMP, how does one detect and enumerate all C++ AMP accelerators?
Don McCrady distributed an app here that enumerates non-emulated accelerators. Though I had a DX11 card (GTX 260), I didn't see any available accelerators. Daniel Moth shows here how to query an individual accelerator, but I couldn't find how do en... | Looks like it's pretty simple: concurrency::get_accelerators(); Daniel Moth comments:
in the VS 11 Developer Preview bits, you simply call concurrency::get_accelerators();. We are working to make that more discoverable for the Beta, whenever that is.
Here's my code:
#include <iostream>
#include "stdafx.h"
#include "a... |
7,533,795 | 7,533,881 | using bitset with floating types | Can you have bitset container of floating data types? Example:
bitset<sizeof(float)*sizeof(char)> second(5.5f);
cout << second.to_string() << endl;
It doesn't work correctly. what i'm trying to do is get the bit representation.
| bitset only takes a unsigned long as its constructor argument. In your example the float is converted to unsigned long and then used as the argument.
To get what you desire use something along the lines of:
float f = 5.5f;
std::bitset<sizeof(float)*CHAR_BIT> foo(*reinterpret_cast<unsigned long*>(&f));
This reinterpret... |
7,533,812 | 7,534,201 | Passing STL and/or MFC objects between modules | I have a rather large code base that is highly modular (lots and lots of plugins), and very often need to pass strings and such between modules. For reference, the code:
only compiles in MSVC/Visual Studio, and very clearly does not and will not support other compilers. Supporting them is not a concern.
only runs on W... | An extension DLL will share the MFC DLL with the application and any other extension DLLs, so that objects may be passed freely between them. Microsoft may have intended for extension DLLs to implement extended classes, but that's not a requirement - you can use it any way you want.
The biggest danger with the standard... |
7,533,873 | 7,534,043 | C++ File list with all file informations | I'm planning to make a program that would work between a folder on my computer and my NAS.
It would list all the files in both folders, then determine which file is newer, and then upload it to the other device.
I know how to upload files via FTP, but I'm stuck at the start, because I don't know how to list my files. ... | FindFirstFile() and FindNextFile() does let you list subdirectories. One of the members of WIN32_FIND_DATA is dwFileAttributes which will include FILE_ATTRIBUTE_DIRECTORY for a directory entry. Simply start another FindFirstFile() in that subdirector, rinse, repeat.
There is a sample on MSDN that shows how to use the... |
7,534,100 | 7,534,113 | Must template parameters be types? | In the Bjarne Stroustrup C++ Book (chapter 13, page 331), it said that "a template parameter can be used in the definition of subsequent template parameter". And it gives the following code:
template<class T, T def_val> class Cont{ /* ... */ }
Can anyone provide an example of how to use this template. For example, how... | You can do something like this:
Cont<int, 6> cnt;
// ^ as long as this is of type T (in this case int)
// def_val will be of type int and have a value of 6
Template parameters aren't required to be types.
This only works when T is an integral type (int, unsigned, long, char etc but not float, std::string, const... |
7,534,257 | 7,534,405 | Register to the DeviceManager of Linux | I read some questions here but couldn't really find the specific problem I'am faced with here...
I need to implement a "DeviceCache" in a particular project which caches all device-names found in /proc/net/dev .
The Language is C/++
So I thought about a seperate thread looking every X seconds in the directory mentioned... | Based on your comments, what you really want is to track which network interfaces are operational at any given time.
The only true way to determine if a network interface is up is to test it - after all, the router on the other end may be down. You could send pings out periodically, for example.
However, if you just wa... |
7,534,504 | 7,534,534 | Is STL Vector calling a destructor of a not-allocated object? | The folowing code shows an output not expected:
class test
{
public:
test()
{
std::cout << "Created" << (long)this << std::endl;
}
~test()
{
std::cout << "Destroyed" << (long)this << std::endl;
}
};
int main(int argc, char** argv)
{
std::vector<test> v;
test t;
v... | Everything is as it should be: there's the local variable t, which gets created and then destroyed at the end of main(), and there's v[0], which gets created and destroyed at the end of main().
You don't see the creation of v[0] because that happens by copy or move constructor, which your test class doesn't provide. (S... |
7,534,505 | 7,534,639 | Disabling optimizations in an executable and maintaining them in a static library | I've come across an odd situation and my (supposed) knowledge of code linkage is failing me...
I have come across a bug that only occurs in a 64-bit build with optimizations turned on (/O2, /O3, or /Ox). The bug occurs in an executable that is not performance critical and we have to give a demo of a prototype very soo... | Your problem is almost assuredly that critical inlining of functions in your library or the standard library is being disabled in the final application by turning off optimizations.
|
7,534,769 | 7,535,237 | C++ doesn't convert string from data | I want to write a little program which should be used in supermarkets. everything is fictitious and it's only for learning purposes.
However, The tool generate a new data for every new article. in the data there are 2 lines, the name and the prise.
The data is named as the article number of the product. So the user ent... | First, you have a using namespace std; somewhere in your code. This occasionally leads to subtle bugs. Delete it. ( Using std Namespace )
int ware::load()
{
string inhalt;
cout << "please insert article number" << endl;
cin >> articlenumber;
The type of articlenumber is incorrect. Declare it std::str... |
7,535,285 | 7,535,730 | Template Type input used as Template Type for Member Property C++ | So I am trying to have one template class be a container (that will later operate on) a set of contained classes, also generated from a template, and stored in a vector.
The abstracted form of what I'm trying to do would look like this:
template <typename T, size_t numberofapples>
class Apples {
public:
... | As @MSN mentioned, you need to use nested templates. In your case they take the form of:
template<typename T, size_t nr, template <typename, size_t> class FruitType>
class Tree { ... };
And they are used this way:
Tree<double, 20, Apple> someTree;
Real example from the code you have provided (compiles under VC++ 2010... |
7,535,299 | 7,535,488 | How to format numbers to significant digits using STL | I'm trying to format numbers to a specific number of significant digits using C/C++ and preferably STL. I've seen examples of doing this in Javascript (toPrecision()) and .Net, but I can't find anything on doing this in C/C++. I want to create a function something like this:
std::string toPrecision(double value, int ... | Stolen from another question:
#include <string>
#include <sstream>
#include <cmath>
#include <iostream>
std::string toPrecision(double num, int n) {
https://stackoverflow.com/questions/202302/rounding-to-an-arbitrary-number-of-significant-digits
if(num == 0) {
return "0";
}
double d = std::ceil... |
7,535,303 | 7,535,369 | From CObArray to ArrayList | I have some pieces of C++ code that store objects in CObArray. I want to re-code the same pieces in Java using ArrayList to store the same objects. Will there be any difference in the overall efficiency?
So is ArrayList the exact correspondent class for CObArray?
| I didn't know what a CObArray was: CObArray is part of MS's C++ implementations.
They description of a CObArray sounds like it behaves in a similar fashion to an ArrayList. That is, in terms of implementation and performance. You should bare in mind that the interfaces will differ for sure. For example, Java's ArrayLis... |
7,535,462 | 7,535,490 | Why is the static keyword needed in this template code? | Working on a simple example for template functions. The code compiles and works as expected. But my question is why "static" is required in both "Cmp" and "Lit"? Otherwise, it will not compile?
Thanks a lot!
template<class T> class Cmp{
public:
static int work(T a, T b) {
std::cout << "Cmp\n";
retur... | The reason that static is required here is that in the compare template function, you have this line:
return C::work(a, b);
The syntax C::work(a, b) here means "call the function work nested inside the class C. Normally, this would try to call a member function without providing a receiver object. That is, typically... |
7,535,546 | 7,535,621 | Template type constructor parameters | Given a template class:
template<class T>
class Foo
{
public:
void FunctionThatCreatesT()
{
_object = new T;
}
private:
shared_ptr<T> _object;
}
Is it possible to somehow pass a set of constructor parameters for T to Foo (perhaps when Foo is constructed) such that Foo can use them when it creat... | Exactly that, variadic templates and perfect forwarding via std::forward.
#include <memory>
#include <utility>
template<class T>
class Foo
{
public:
template<class... Args>
void FunctionThatCreatesT(Args&&... args)
{
_object = new T(std::forward<Args>(args)...);
}
private:
std::shared_ptr<T... |
7,535,638 | 7,536,715 | Question regarding NTFS Change Journal USN records | This maybe a somewhat silly question, but I haven't been able to find the answer anywhere.
Is there any way to find out what the last record in the change journal is?
When we run the FSTCL query for the first time it takes too long to enumerate all the records. Is there a easy way to find it?
| FSCTL_QUERY_USN_JOURNAL returns the USN that will be used for the next record (NextUsn). The last record will normally be NextUsn minus 1. To play it safe, you could use FSCTL_ENUM_USN_DATA with USN filtering to look for NextUsn minus 1, and if it doesn't exist look for NextUsn minus 2, then minus 4, etc.
|
7,535,726 | 7,535,778 | Is garbage collection detrimental to the performance of this type of program | I'm building a program that will live on an AWS EC2 instance (probably) be invoked periodically via a cron job. The program will 'crawl'/'poll' specific websites that we've partnered with and index/aggregate their content and update our database. I'm thinking java is a perfect fit for a language to program this applica... | No, your concerns are most likely unfounded.
GC can be a concern, when dealing with large heaps & fractured memory (requires a stop the world collection) or medium lived objects that are promoted to old generation but then quickly de-referenced (requires excessive GC, but can be fixed by resizing ratio of new:old space... |
7,535,743 | 7,535,953 | Organizing static data in C++ | I'm working on some embedded software where there is some static information about "products". Since the information for a certain product never changes during execution I would like to initialize these data structures at compile time to save some space on the stack/heap.
I made a Product class for the data, intending ... | An old school C style static array of structs sounds like a perfect match to your requirements. Initializes at compile time, zero runtime overhead, no use of stack or heap. It's not a co-incidence that C is still a major player in the embedded world.
So (one recipe - plenty of scope to change the details of this);
// i... |
7,535,899 | 7,535,910 | Unobtrusive Windows Notifications | I'm looking for a simple solution to create an unobtrusive notification program for windows using c++/QT/WinAPI/SDL or any other quick library. I'm wondering what the fastest method (as far as development goes) to create a simple program that pops a quick window up with access to a larger gui interface if clicked.
Is ... | You may want to have a look at Growl for Windows.
|
7,536,017 | 7,536,038 | Problems with pointers | I have a Binary Search Tree that I'm making and I implemented the Insert node code as follows:
BSTNode * BST::Insert(const std::string & v){
BSTNode * node = new BSTNode(v);
if (root == NULL){
root = node;
} else if (root->value.compare(v) > 0) {
Insert(root->left, node);
//recursive... | The problem here is that current is a local variable with a copy of the value of the pointer. It's not the same variable that you pass in. If you want to modify the pointer in place, your method should accept either a pointer to the pointer or a reference to the pointer. The easiest way to do this would be to just m... |
7,536,153 | 7,536,230 | Byte-for-byte copies of types in C++11? | The C++11 standard guarantees that byte-for-byte copies are always valid for POD types. But what about certain trivial types?
Here's an example:
struct trivial
{
int x;
int y;
trivial(int i) : x(2 * i) { std::cout << "Constructed." << std::endl; }
};
If I were to copy this struct, byte-for-byte, is it guarantee... | Yes, it is guaranteed to copy properly.
Quoting the FDIS, §3.9/2:
For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes making up the object can be copied into an array of char or unsigned char. If the content of t... |
7,536,271 | 7,536,561 | C++: Why does casting as a pointer and then dereferencing work? | Recently I have been working on sockets in C++ and I have come across this:
*(struct in_addr*)&serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;
While this does do what I want it to I am a little confused as to why I can't do this:
(struct in_addr)serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_a... | A simpler example might help to explain the difference:
double q = 0.5;
int n;
n = (int) q; // #1
n = *(int*)(&q) // #2
The first version converts the value of q into a value of type int according to the rules of the language. Conversion is only possible for primitive types and for classes that define conversion o... |
7,536,439 | 7,536,483 | Casting a C++ long type to a JNI jlong | I am using JNI to pass data between C++ and Java. I need to pass a 'long' type, and am doing so using something like:
long myLongVal = 100;
jlong val = (jlong)myLongVal;
CallStaticVoidMethod(myClass, "(J)V", (jvalue*)val);
However in Java, when the 'long' parameter is retrieved, it gets retrieved as some very large... | When you pass a jlong (which is 64 bit) as a pointer (which is, most likely, 32-bit) you necessarily lose data. I'm not sure what's the convention, but try either this:
CallStaticVoidMethodA(myClass, "(J)V", (jvalue*)&val); //Note address-of!
or this:
CallStaticVoidMethod(myClass, "(J)V", val);
It's ...A methods tha... |
7,536,445 | 7,536,900 | C++ Windows link subsystem question | When using the windows SDK to compile a program writen in C++, if I specify -subsystem:windows,6.1,
the width of the window is smaller. If I don't, or do -subsystem:windows without the 6.1, the width is normal.
I'm curious why this does this, and if there's a way to make it stay the same width regardless of what comman... | I'm suspecting you are specifying some windows styles that are only supported in Windows7 (Win7 = 6.1). Post the full CreateWindow call with arguments and also try turning off Aero. The window border may be included in the width/height for example in one scenario.
|
7,536,470 | 7,536,509 | Quick C++ data to Java transfer | I'm trying to transfer a stream of strings from my C++ program to my Java program in an efficient manner but I'm not sure how to do this. Can anyone post up links/explain the basic idea about how do implement this?
I was thinking of writing my data into a text file and then reading the text file from my Java program bu... | Text files can easily be written to and read from upwards with 60 strings worth of content in merely a few milliseconds.
Some alternatives, if you find that you are running into timing troubles anyway:
Use socket programming. http://beej.us/guide/bgnet/output/html/multipage/index.html.
Sockets should easily be fast eno... |
7,536,711 | 7,536,746 | problem with an abstract type as class member variable | I try to use a abstract class type as a member variable in my class definition, but somehow it has some problem. Here is the abstract class type:
class POINT{
public:
virtual int point_dim() = 0;
/*other virtual functions...*/
}
And here is the inherited class:
class POINTX : public POINT{
public:... | POINT declares:
virtual int point_dim() const = 0;
Therefore POINTX must have a const method called point_dim:
int point_dim() const {return 10;}
Without this, it will have two point_dim() methods, one non-const and one const but pure virtual, leaving POINTX as abstract.
As long as func() takes a reference to a... |
7,537,008 | 7,537,109 | Compilation error while using librsvg | I am using librsvg in my C files to rasterize SVG, but as soon as I include rsvg.h, I start to get the following error:
/usr/include/librsvg-2.0/librsvg/rsvg.h:29:25: fatal error: glib-object.h: No such file or directory
Does anyone know why it is happenning and how to get rid of it? I tried including the path of gl... | You might want to use pkg-config to get the proper flags to add, like this:
g++ -c -o renderSVG.o renderSVG.cc $(pkg-config --cflags librsvg-2.0)
g++ -o renderSVG renderSVG.o $(pkg-config --libs librsvg-2.0)
|
7,537,021 | 7,537,064 | Needing an elegant solution to a simple, C++ bingo board | I'm trying to code a Bingo Board in C++, but I'm doing something very wrong. I'm not sure what, but for whatever reason when I initialize the number of rows and columns, and do a nested for loop on the arrays I created to implement this structure, I get what appears to be more than a hundred rows and 30+ columns, when ... | In order to create the 2-dimensional board your wanting, where the size is input at runtime, you're going to have to actually dynamically allocate a board in memory ... you can't declare your board the way you've done in your class as zero-length arrays.
Code like this:
this->m_rows[numberOfRows];
does not initialize ... |
7,537,022 | 7,537,028 | Why is std::bitset::at() throwing out_of_range? | This has stumped me for a few hours now, since I cannot see any problem in the math or code. (Dispite staring at it and working it out over and over again to be sure.) I'm hoping you folks can help me, here's my code:
#define SOLVE_POSITION(x, y, z) ( z*16 + y*4 + x )
std::bitset<64> block;
block.reset();
for(i... | Macros! You have to be really careful about this:
You define:
#define SOLVE_POSITION(x, y, z) ( z*16 + y*4 + x )
so when you do:
SOLVE_POSITION(3-x, y, 3-z)
it expands to:
( 3-x*16 + y*4 + 3-z )
and because of operator precedence, 3-x*16 will be incorrect! You need to do:
#define SOLVE_POSITION(x, y, z) ( (z)*16... |
7,537,262 | 7,537,297 | Binary search tree insertion | Need help to figure out why the following code for basic Binary Search Tree insertion is not working. Since I have been working on C# for sometime now, I'm afraid I forgot some of my C++. Also, any suggestions to improve coding style would be very helpful. (I know I'm not freeing memory as of now)
struct Node
{
... | It appears to me that
Insert(cRoot->data, cRoot->lChild);
should instead be
Insert(newData, cRoot->lChild);
|
7,537,288 | 7,537,302 | Interactive console programming for c/c++? | So I've written a small program which takes in commands by the users, and then displays the output (after connecting to a server). It's an interactive console of sorts.
However, after using the mongodb and redis command-line clients (which work interactively on the console/terminal), it seems that there must be a libra... | The readline library is a common choice: http://www.gnu.org/s/readline
If you are more ambitious, ncurses gives you more control, but has less functionality to begin with and a steeper learning curve.
Edit:
icktoofay mentioned that readline is licensed under the GPL. If this is a problem for your software, tecla is an ... |
7,537,300 | 7,537,325 | Not Able to include header file? | Hi I have created a project in vs 2005. I have created a header file A.h.
Similarly I have added A.cxx in a folder called implementation. In .cxx file I have included A.h.
I have used #include "A.h". But when I am compiling it is telling A.h not found.
| You can include files one of two ways:
As a relative path to your .cpp file (example assumes a.h is in a folder above your .cpp file)
#include "..\a.h"
Or by adding the header location to your project include directories
Right click on project, goto properties, under configuration properties, goto VC++ Directories (... |
7,537,491 | 7,537,555 | QVector.push_back error | error in
QVector<LibraryRecord> Library;
Library.push_back(LibraryRecord(DateOfIssue, ReturnDate, FIO,tTekct,FName,TText));
error message:
no matching function for call to ‘LibraryRecord::LibraryRecord()’
why? Constructor present
//constructor
LibraryRecord::LibraryRecord(QString pDateOfIssue,
... | Unlike the C++ Standard Library containers (e.g. std::vector), the Qt containers require that the value type be default constructible.
That is, your type LibraryRecord must also have a default constructor (the constructor that you show, which requires arguments, is not a default constructor).
|
7,537,791 | 7,537,933 | Understanding Recursion to generate permutations | I find recursion, apart from very straight forward ones like factorial, very difficult to understand. The following snippet prints all permutations of a string. Can anyone help me understand it. What is the way to go about to understand recursion properly.
void permute(char a[], int i, int n)
{
int j;
if (i == n)... | PaulR has the right suggestion. You have to run through the code by "hand" (using whatever tools you want - debuggers, paper, logging function calls and variables at certain points) until you understand it. For an explanation of the code I'll refer you to quasiverse's excellent answer.
Perhaps this visualization of the... |
7,537,815 | 7,537,830 | function declaration scope | Most people seem to declare functions outside the code block that's using them like this:
void doSomething();
void doStuff()
{
doSomething();
}
I'm wondering if it's considered a good habit to do instead like this:
void doStuff()
{
void doSomething();
doSomething();
}
The second method has smaller scope... | As the function has to be defined in the enclosing namespace scope, there doesn't seem to be a great advantage in restricting the declaration to the function scope.
Conventionally, having a single declaration in a header file is easier to maintain as, if the function definition needs to change, only a single declaratio... |
7,537,820 | 7,537,827 | How do you concatenate two strings? |
Possible Duplicate:
How do I concatenate multiple C++ strings on one line?
How would I take:
string test1 = "Hello ";
string test2 = "World!";
and concatenate them to make one string?
| How about
string test3 = test1 + test2;
Or maybe
test1.append(test2);
|
7,537,843 | 7,551,161 | Valgrind program is crashing Bad permissions for mapped region at address | I am trying to run my program to check memory leaks in my program but whenever I start my program I am getting
==3476== Process terminating with default action of signal 11 (SIGSEGV): dumping core
==3476== Bad permissions for mapped region at address 0xCFE3FF8
==3476== at 0x005212e1: get_document_root (mongoose.c:1... | It was crashing because of custom 404 page and that file was not there. So it was infinitely looking for that file and doing buffer overflow.
|
7,537,874 | 7,537,880 | How do you convert an int into a string in c++ | I want to convert an int to a string so can cout it. This code is not working as expected:
for (int i = 1; i<1000000, i++;)
{
cout << "testing: " + i;
}
| You should do this in the following way -
for (int i = 1; i<1000000, i++;)
{
cout << "testing: "<<i<<endl;
}
The << operator will take care of printing the values appropriately.
If you still want to know how to convert an integer to string, then the following is the way to do it using the stringstream -
#inclu... |
7,537,945 | 7,537,999 | Generate all ways of selection of n items |
Possible Duplicate:
How to find all possible subsets of a given array?
How can all ways of selection of items be generated efficiently using C++?
For example, if there are there items A, B and C.
[A,B,C] => [A], [B], [C], [A,B], [B,C], [A,C], [A, B, C]
| For that input set:
#include <iostream>
void print(int b, char *a, int n)
{
for(int i = 0 ; i < n ; i++)
{
if( b & 0x1) std::cout << a[i];
b = b >> 1;
}
std::cout << std::endl;
}
int main() {
char a[] = {'A','B','C'};
for(int i = 1 ; i < 8 ; i++ )
print(i,a,3);
... |
7,538,006 | 7,538,055 | Prevent Windows shutdown with custom message | VMWare Workstation does something quite cool when I try to shutdown Windows while a Virtual Machine is running:
Normally, we'd see a "This program is preventing Windows from shutting down" message instead of the new "1 Virtual Machine is in use".
How does VMWare do this? I haven't been able to find any APIs about it ... | You can read all about the changes introduced in Vista here. You really should read that article very carefully.
The APIs you are looking for are ShutdownBlockReasonCreate, ShutdownBlockReasonDestroy and ShutdownBlockReasonQuery. Remember that these APIs are only available on Vista/2008 server up. You'll have to implem... |
7,538,062 | 7,538,079 | Does boost::variant work with std::string? | I've written a simple program in C++ with use of boost::variant. Program's code is presented below.
#include <string>
#include <iostream>
#include <boost/variant.hpp>
int main (int argc, char** argv)
{
boost::variant<int, std::wstring> v;
v = 3;
std::cout << v << std::endl;
... | The problem is that wstring cannot be << in cout. Try using wcout instead. This is not a problem with the variant.
|
7,538,115 | 7,538,228 | Return a value to external invoker C++ | I am invoking a C/C++ program (exe) from C#, I want to return a float value from my C/C++ to the C# code, I have the exe code which writes file a for a single value, instead I want to return that value to C#. How can I do that?
| You could output the result of your C/C++ program to the standard output, and then parse it with C# after the invokation.
Check this answer: Best Way to call external program in c# and parse output
Or if your program is called a lot a time, maybe a better solution would be to let it run and communicate with your C# pr... |
7,538,174 | 7,538,710 | Using const_iterator when overloading a const operator[] | I really do not understand what I am doing wrong below. I have a class named Settings with the structure listed below, and two of the functions listed below as well. What I am having trouble with is specifically where to put the const modifiers when overloading a const operator[] within the overloading function. Do I n... | Your problem is not with the const but with references.
Also your declarations in the class must match exactly the definitions you use when defining the functions.
class Settings
{
map<string, string> settingsMap;
map<string, string>::const_iterator itc;
const& string getValue(const string& K) const;
... |
7,538,264 | 7,538,528 | Using std::complex with iPhone's vDSP functions | I've been working on some vDSP code and I have come up against an annoying problem. My code is cross platform and hence uses std::complex to store its complex values.
Now I assumed that I would be able to set up an FFT as follows:
DSPSplitComplex dspsc;
dspsc.realp = &complexVector.front().real();
dspsc.imagp = &compl... | The std::complex functions real() and imag() return by value, they do not return a reference to the members of complex.
This means that you cannot get their addresses this way.
|
7,538,431 | 7,538,521 | Compiler requirement for override and final | I can remember that during the discussion about general attributes which finally lead to the new contextual keywords override and final it was suggested that compiler support for these ore some may be optional (I guess it would read in the standard text as "behavior is implementation-specific). But I can not find any t... | Yes, it's required that override is not ignored by a conforming implementation. First, override can only appear in the declaration of a virtual member function.
9.2/9:
[...] A virt-specifier-seq shall appear only in the declaration of a virtual member function.
Second, a virtual function which doesn't override a memb... |
7,538,448 | 7,538,470 | Adding two unsigned char variables and result is int | There is code:
#include <iostream>
int main(){
unsigned char a = 4, b = 255;
int g = (unsigned char)a + (unsigned char)b;
std::cout << g << std::endl;
return 0;
}
Result:
259
Why the result is 259, not 3? If there are added two unsigned char variables, there should be overflow, result should be 3 and then it ... | The addition operation will first promote its operands to int, before doing the addition. This is how C works. If you want to truncate, you need to assign it back into a narrower type, such as unsigned char.
|
7,538,514 | 7,539,285 | not able to locate entry point for a method in dll? | Hi I have a class and I wrote few methods in it. Then I created dll for that class. Now i commented out few methods and then again created dll for the class. But now when i am loading the dll in one of the exe I get the error poped out like this,"NOt able to locate entry point for abc method in xyz dll".
| Did you recompile the exe?
If not, then please, recompile it, because something has changed in the DLL API.
If yes, then you probably are linking with the old LIB file instead of the new one, and something has changed in the DLL API.
|
7,538,659 | 7,538,736 | Convert C++ to MIPS assembly | This code is about to find maximum element from an array i want to convert this code into MIPS assembly code can anyone help me...Or just tell me how to initialize an array in MIPS.
void max_array()
{
int a[10]={2,3,421,4,32,4,3,1,4,5},max;
for(int i=0;i<9;i++)
{
cout<<a[i];
}
max=a[0];
... | Here's an example
.data
array1: .space 12 # declare 12 bytes of storage to hold array of 3 integers
.text
__start: la $t0, array1 # load base address of array into register $t0
li $t1, 5 # $t1 = 5 ("load immediate")
sw $t1, ($t0) ... |
7,538,883 | 7,539,034 | Multiple WndProc functions in Win32 | This might be a dumb question, but can you register multiple WndProc functions in Win32? e.g. a framework catches some messages and my app is interested in other ones - how do I catch them without modifying the framework code?
| If I understand your intention correctly, you can do that by setting a hook. Assuming you know the thread whose message loop you'd like to hook, you can do something along these lines (unchecked):
SetWindowsHookEx(WH_CALLWNDPROC, yourHOOKPROC, NULL, theThreadId);
|
7,538,888 | 7,544,489 | Generalized chaining of non-member functions in C++ | I don't know if this can even be achivieable, but given these set of functions\class:
float plus1(float x) { return x+1; }
float div2(float x) { return x/2.0f; }
template <typename T>
class chain {
public:
chain(const T& val = T()) : val_(val) {}
chain& operator<<( std::function<float (float)> func ) {
val_... | A general and extendable solution using boost::proto :
#include <iostream>
#include <boost/proto/proto.hpp>
namespace bp = boost::proto;
// -----------------------------------------------------------------------------
// perform is a callable transform that take a function_ terminal and execute it
// ----------------... |
7,538,954 | 7,538,972 | Implementing push/pop in a linked list (C++) | I'm trying to incorporate push/pop into a linked list and I can't seem to get it to work. When I run my test function, I set my linked list to zero and I try to push on values but the list keeps getting returned with no values in it. Could anyone possibly tell me what I'm doing wrong?
| if (top == NULL){
current = top;
current->next = NULL; //NULL->next : will cause segfault
}
if top is NULL, you set current = top [which is NULL], and then you access current->next, which will cause a segfault, you are trying to access NULL..
EDIT: follow up to comments:
your if statement seems redundant... |
7,538,990 | 7,540,776 | Does libpcap watch sent packets? | Does pcap_next display packets that were sent?
For example:
If I ping google.com while libpcap is listening for packets, then run pcap_next twice, will both of the returned values be a packet, or will one of them be null?
Edit:
Yes it does.
| Yes, it does.
And here is some extra text to satisfy the rules.
|
7,539,113 | 7,539,379 | Deleting a doublepointer (matrix) | I am solving a quantum-mech problem which requires me to find some eigenvalues by manipulating some matrices. The specifics of this problem is not relevant, I just need help with the c++ problem, I am new to this language and after a couple of hours I figured any more attempts at solving it myself would be futile and s... |
According to my professor I have to deallocate in the same function as I allocate
That is pure silliness. Sometimes (almost always) you need to use the allocated struct outside the function. Definitely false for objects, since constructors and destructors are different functions.
Any way, you can get away without us... |
7,539,154 | 7,539,498 | C++ Windows font size question | First i'm using the windows api.
So I have an edit control, that needs to be able to fit 22 characters max.
Currently only 12 fit with the font I'd like to use.
Is there any way to resize the font well the user is typing to allow for more text to fit without creating a bunch of fonts?
| Well, you could. Implement a message handler for EN_CHANGE so you know the text was changed. Use GetWindowDC and DrawTextEx with the DT_CALCRECT and DT_EDITCONTROL flags to measure the size of the text. Send WM_SETFONT to change the font for the control if it doesn't fit and repeat.
The user being pleased with the en... |
7,539,282 | 7,539,330 | Order of calling constructors/destructors in inheritance | A little question about creating objects. Say I have these two classes:
struct A{
A(){cout << "A() C-tor" << endl;}
~A(){cout << "~A() D-tor" << endl;}
};
struct B : public A{
B(){cout << "B() C-tor" << endl;}
~B(){cout << "~B() D-tor" << endl;}
A a;
};
and in main I create an instance of B:
int... |
Construction always starts with the base class. If there are multiple base classes then, construction starts with the left most base. (side note: If there is a virtual inheritance then it's given higher preference).
Then the member fields are constructed. They are initialized in the
order they are declared
Finally, th... |
7,539,336 | 7,539,383 | Using RGB colors in Assembly Language | I am Plotting a pixel on the screen from the following code using Assembly Language of x86 processor in C++. I dont want to use any function or method from C++ as I use this code for the boot loader program. here is the code:
/**********************************
* Mainvainsoft 2011. *
* Writen By: Farid-ur... | Mode 13h uses a palette with 256 18-bit RGB (6 bits for each) entries. So you can set for example entry 4 to the RGB color you want and the plot the pixel as you are doing with color 4.
See here for an example of how to set a palette entry. After setting the video mode you can do something like:
// Set entry 4
mov dx, ... |
7,539,538 | 7,539,685 | Recipe for `final`: omit `virtual`? | Is it a valid recipe to say that if I write final (to a member function) one should not write virtual?
In a base class, final methods would make no sense:
struct Driver {
virtual void print();
};
If one would add final to print() this would defy the reason for polymorphism in the first place. So that would be usel... | Your analysis is correct. Not marking a final member as virtual avoids declaring a new, non-overriden member and catches mistakes. However, since that's the purpose of override, it may be simpler to just use final override; then whether the member is marked virtual or not won't matter at all.
|
7,539,614 | 7,539,652 | What do this expression mean? (SetConsoleTextAttribute function in C) | I'm in a the middle of creating a console based small game for our C programming class assignment and I decided to make it more presentable and unique by adding text colors and text backgrounds.
While I was on my quest searching for a solution, I've found this handy function that will do just the way I wanted for my pr... | ForgC and BackC are two values that can really only expand to take up of 4 bits each (you can tell this because they are being bitwise ANDed with 0x0F, which clears all but the last 4 bits of the first operand).
So if we look at them as 8-bit wide values, they would be of the form
ForgC 0000xxxx
BackC 0000yyy... |
7,539,711 | 7,540,702 | C++ WM_NCCALCSIZE not being sent | I'm trying to center the text in a edit control vertically, after some research I found I have to process the WM_NCCALCSIZE message.
So i've subclassed my edit control, but the WM_NCCALCSIZE message is never sent.
Am I doing something wrong?
EDIT:
So i'm processing the WM_NCCALCSIZE message fine, and I have a 3d border... | Figured it out, WM_NCCALCSIZE is sent before the edit control is subclassed.
So i had to superclass the EDIT class.
EDIT:
Another solution I just thought of would be to subclass it, then call SetWindowPos with SWP_FRAMECHANGED, this causes it to send the WM_NCCALCSIZE message.
If anyone has any opinions why one method ... |
7,539,716 | 7,543,813 | Implementing meta-function zip in c++11 | I am actually trying to see if I can get a minimal library that supports the very few operations I use from boost::fusion.
Here is what I have so far...
template < typename... Types >
struct typelist
{
};
template < template < typename... > class F, typename... Args >
struct apply
{
typedef typename F < Args... >:... | This is the shortest implementation I've discovered:
template <typename...> struct typelist { };
template <typename A,typename B> struct prepend;
template <typename A,typename B> struct joincols;
template <typename...> struct zip;
template <typename A,typename... B>
struct prepend<A,typelist<B...> > {
typedef... |
7,539,738 | 7,539,768 | partial class templates specialization, c++ | I'm trying to figure it out, so I have this attempt of specializing a class template:
template <class T, int size> class arr{
public:
arr(T* in):_in(in){};
void print()
{
for (int i = 0; i < size; i++)
{
cout << _in[i];
}
cout << endl;
}
private:
T* _in;
}... | template <int size> class arr<char, size>
Also, you may want to change the type for size to an unsigned int or size_t (assuming size cannot be negative).
|
7,539,813 | 7,539,871 | VS2010 C++ Win32 API intellisense | Is where any extension, for visual studio, to support intellisense for c++:
win32api,mfc,atl whatever. Or its supported, and only i can not see it?
Or any workaround or other IDE?
For example:
int main(){
Set
}
And here i want to see all available winapi functions, which starts from "Set". Is it possible?
| In the following snippet:
#include <Windows.h>
int main ()
{
::Set
}
I get all completions for Win32 API functions starting with Set. If you don't like having all those references to the global namespace, you can hit Control-Space to force intellisense to show completions.
|
7,539,857 | 7,539,921 | Reflections on C++ Variadic Templated Versions of std::min() and std::max() | I need reflections on my implementations of the C++11 variadic versions of std::min, std::max. Here are my two alternatives for std::min, where std::max is implemented analogously by just replacing std::min with std::max:
/*! Multi-Type Minimum of \p a. */
template <LessThanComparable T> const T & multi_type_min (const... | Can't you just write it such that it recurses until you stop at two parameters?
Here's a (untested) snippet:
/*! Multi-Type Minimum of \p a and \p args. */
template <class T, class U >
//requires SameType <T , U >...
T multi_type_min(const T & a, const U & b)
{
return std::min(a, b);
}
/*! Multi-Type Minimum of \p... |
7,539,917 | 7,539,936 | Incorrect values from GetProcessHandleCount | I faced with strange behavior of function GetProcessHandleCount().
At first I take a snapshot of all processes in the system as it is described in msdn:
HANDLE hProcessSnap;
HANDLE hProcess;
PROCESSENTRY32 pe32;
hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
pe32.dwSize = sizeof( PROCESSENTRY32 );
i... | For one thing, GetProcessHandleCount might return zero (which signifies an error). This could explain coming to a result lower than what you expect. This might be caused in turn by OpenProcess failing (you don't check for that either).
|
7,540,428 | 7,740,408 | SAX2 (Xerces-C): How to get the line number of parsed tags? | I parse an XML file in C++ using the SAX2 api of Xerces-C.
So I do implement the DefaultHandler interface and its functions
void startElement(
const XMLCh* const uri,
const XMLCh* const localname,
const XMLCh* const qname,
const xercesc::Attributes& attrs
);
and
void endElement(
... | Override the setDocumentLocator() method in your class derived from xercesc::DefaultHandler to get hold of the xercesc::Locator object. You can then call its getLineNumber() method.
|
7,540,500 | 7,543,200 | No output when running C++ applications via Eclipse CDT IDE | Eclipse can build my applications for me so far, and I can execute them directly (via Windows 7 Explorer), but I get no results when I use the run command via the CDT perspective. The console tab only tells me that the application terminated, even with a console app with input (cin >> and so forth). Win32 apps don't ex... | Solved it! It's because my workspace was in the "Program Files" directory, which has a space in it. Probably a MinGW issue.
Thanks to Keith Thompson for the help though!
|
7,540,554 | 7,540,588 | Implementing fa unction that adds and sorts data in a singly linked list (addsort)? | I'm very new to C++ so it's a bit hard to understand the syntax sometimes. Anyways, I'm supposed to implement a function that adds and sorts the data given into a linked list. For example if I pass 2 into the list [1,4,5] then I should get [1,2,4,5]
Here is what I have written so far, and no it does not work, I keep ge... | Hope that you have really put your effort in it..I am posting the whole function for inserting data into list in sorted order which I had written long time back
void addData(node * head, int data){
if(head == NULL) { // First node
node * temp = new node;
temp -> data = data... |
7,540,697 | 7,540,749 | Using fscanf to set a variable in a different class | I'm trying to read a number from a file and set it to a public variable in a different class. The function that is reading the file has a pointer-object instance of that class. I'm facing a weird issue:
The following works:
int dummy;
fscanf(file,"%d",&dummy); // assume the file stores the number 10
globals->var = dum... | As you said in the comment, the type of var is double. Yes, that is the problem. You should use %f for it.
Apart from that, I would give you a piece of advice:
Prefer using C++ stream for I/O work. They're type-safe. If you use them, you would not face this problem which you faced it with fprintf.
Here is how you shoul... |
7,540,699 | 7,540,728 | Difference between std::string's operator[] and const operator[] | Can anyone please explain the difference between:
const char& operator[] const
and
char& operator[]
in C++?
Is it true that the second one is duplicating the string? and why?
| They both return references to the internal member of the string.
The first method is defined as a const method (the last const) and as such promises not to change any members. To make sure you can;t change the internal member via the returned reference this is also const.
const char& operator[](int i) const
// ... |
7,540,730 | 7,540,818 | Debugging C++ code involving use of: vector, string, STL | I am C++ beginner. When I try to debug C++ code using following constructs like string, vector of certain native types, STL etc, debugging gets tedious. I use MS Visual Studio 2010/ Visual C++ 2010 Express.
e.g.
-- While using string as below:
string str;
getline(cin, str);
for(i=0; i<str.size();i++)
Watch window ... | As you have found out, trying to use overloaded operators in the watch window simply won't work. You need to break open the objects and pull out the member variables.
In MSVC, std::vector has a member variable _Myfirst that points to the first element of its buffer. To get the item at index i you can add
(v._Myfirst)... |
7,540,808 | 7,540,907 | Embedding python + numpy code into C++ dll callback | I am new of python embedding.
I am trying to embed python + numpy code inside a C++ callback function (inside a dll)
the problem i am facing is the following. if i have:
Py_Initialize();
// some python glue
// python invocation
Py_Finalize();
everything works fine.
but if i have:
Py_Initialize();
_import_array(); //to... | Try make sure your .dll is only initialized once, regardless of how many times the code is actually invoked.
Here is a link on "C++ Singleton in a DLL":
Singleton in a DLL?
|
7,541,123 | 7,541,163 | Defining variables in control structures | According to the standard, what is the difference in behavior between declaring variables in control structures versus declaring variables elsewhere? I can't seem to find any mention of it.
If what I'm referring to isn't clear, here's an example:
if (std::shared_ptr<Object> obj = objWeakPtr.lock())
As you can see, I'... |
According to the standard, what is the difference in behavior between declaring variables in control structures versus declaring variables elsewhere? I can't seem to find any mention of it.
Declarations inside control structure introductions are no different that declarations elsewhere. That's why you can't find any... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.