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,029,792 | 7,032,481 | Is there a canonical way to reorder the DACL of an object after adding an ACE to it? | After adding an ACE to a file ACL, I checked the permissions on the object using Explorer. It is giving me an error about the DACL not being in canonical format and asks me if I would like it reordered. Is there any sort of documentation anywhere that provides the canonical ordering of the DACL so I don't have to rely... | If you use the SetEntriesInAcl function (as opposed to low-level functions such as AddAce) the ACL will be put in canonical order automatically.
|
7,029,824 | 7,038,419 | Problem with qt + mysql interaction | Now I'm working on Qt project and I need some MySQL support. MySQL was installed on virtual machine (Virtual Box) on Ubuntu Server. Here's what I do:
int main(int argc, char** argv)
{
QApplication app(argc, argv);
QSqlDatabase hospital_db = QSqlDatabase::addDatabase("QMYSQL");
hospital_db.setHostName("192.1... | Well, seems that I had some problems with permissions on server side. Now everything is fine.
|
7,029,949 | 7,030,028 | Scope of DataType declared in Namespace | Sample.h
namespace Testing
{
enum Type
{
DATA = 0,
MORE_DATA
};
}
Now in Sample2.h, using the same namespace, can I access the DataType defined in Sample.h, without including it?
namespace Testing
{
Type test;
}
The question has come up, because I have files that implement this, and se... | Yes, you will need to include Sample.h within Sample2.h. The definition of Type is not visible to the compiler within Sample2.h simply because the namespace name is the same within the 2 files.
The only thing you gain by having the same namespace names in the 2 files is that Type does not need to have its namespace st... |
7,030,051 | 7,030,121 | printf-style logger that is non-variadic | Our C/C++ project is using a new internal script that liberally wraps every function in SWIG to make available to python scripts. It chokes on our logger function since SWIG cannot wrap variadic functions well.
So I decided to hide the variadic functionality in a macro that SWIG will never trip over, shown in a simpli... | Python makes it trivial to assemble formatted strings within Python, so I would just offer the simple "give me a string and I log it" error.
For the general case, though, you might consider:
1) boost::format
2) emulating the iostream interface by creating a class that holds a std::stringstream member, overloading opera... |
7,030,102 | 7,030,431 | c++0x: resolving ambiguity between function-definition followed by empty-declaration and simple-declaration | I am having an issue with wrapping my head around an apparent ambiguity in the c++0x spec, see also: http://www.nongnu.org/hcb/
Assume we have the code
void foo() {};
Personally I interpret the code as a function-definition followed by an empty-declaration. But, looking at the grammar spec, I'd say that this could jus... | I think you are right. It's an ambiguity and I'm not aware of a paragraph that resolves it in the spec.
There are other ambiguities in the C++0x spec that are not explicitly resolved, but that (hopefully) are going to be implemented in the straight forward way by compilers. For example, the following can be parsed as ... |
7,030,719 | 7,030,750 | Is libSoX thread-safe? | I am using libSox, the audio processing library in a multi-threaded application. Several threads may call the libsox functions simultaneously. I was wondering if libsox was thread-safe since I am getting this random crash.
| No it is not completely threadsafe.
This commit here tells so.
|
7,030,861 | 7,031,124 | Simple Method to a Simple Parser | I'm trying to create a simple parser and a small text file which follows the following structure:
Variable_name = Value;
VARIABLE_2 = SECOND_VALUE;
Found methods that work, however, use many librarys like Boost. I wonder if you can make a simple, preferably with only the librarys of STD.
Thanks, Bruno Alano.
| If your format will be staying like you have listed, and there will be no spaces in either the variable names or the values, this is can be done easily using a combination of std::string and std::istringstream. You could simply do the following:
//assume we have an open ifstream object called in_file to your file
stri... |
7,030,953 | 7,034,315 | How can a Solaris process read its own symbol table? | I have a Solaris process, which is a C++ application that is loaded by ld with a few .so libraries. This application has a function that gets a return address in the calling function and then tries to determine the name of the said calling function.
If I use dladdr(3) for that, it does not always put what I expect to s... | I have tried a simple test using dladdr() on Solaris 10/SPARC (but caveats: GCC 3.4, straight C), and this works fine for me:
#include <dlfcn.h>
#include <stdio.h>
void print_name(char *name, void *addr);
void print_name_by_dladdr(void *addr);
int main(int argc, const char *argv[])
{
print_name("main", (void *)&m... |
7,031,202 | 7,031,314 | Sockets in a "group" setting? | Typically you have a server and client pair or two peers that connect to each other through a socket. This is a 1 to 1 relationship.
Lets say you had 6 peers. Is there a way for them to be "grouped" together without a "server" so that 1 peer can send a udp/tcp message directly to another?
I'm basically looking for a wa... | UDP sockets can send data through a non-connected socket using the sendto() function. Endpoints specified have to be listening on the given IP/port but do not have to have already initiated a connection.
|
7,031,210 | 44,969,253 | linux perf: how to interpret and find hotspots | I tried out linux' perf utility today and am having trouble in interpreting its results. I'm used to valgrind's callgrind which is of course a totally different approach to the sampling based method of perf.
What I did:
perf record -g -p $(pidof someapp)
perf report -g -n
Now I see something like this:
+ 16.92% ... | You should give hotspot a try:
https://www.kdab.com/hotspot-gui-linux-perf-profiler/
It's available on github: https://github.com/KDAB/hotspot
It is for example able to generate flamegraphs for you.
|
7,031,462 | 7,031,543 | Problem creating vector of Pairs | I am trying to create a data structure called Disjoint Set. Looking at theory what i thought of is something like this :
std::vector<std::pair<int,std::set<int>>> DisjointSet;
for(auto i=0;i<10;++i) DisjointSet.push_back( std::make_pair(i,std::set<int>().insert(i)));
but this code gives which is beyond my understandin... | set::insert doesn't return the set itself. You need to create the set beforehand, insert and then use it in make_pair. This does the trick with nearly no overhead for the copy using move:
std::vector< std::pair<int,std::set<int> > > DisjointSet;
for(auto i=0;i<10;++i) {
std::set<int> tmp; tmp.insert(i);
DisjointSet... |
7,031,564 | 7,031,589 | Is it safe to remove the const-ness of the stringstream result when performing binary serialization? | I have a situation in which I'm performing binary serialization of a some items and I'm writing them to an opaque byte buffer:
int SerializeToBuffer(unsigned char* buffer)
{
stringstream ss;
vector<Serializable> items = GetSerializables();
string serializedItem("");
short len = 0;
for(int i = 0; i <... | No removing const-ness of an inherently contant string will result in Undefined Behavior.
const char* c_str ( ) const;
Get C string equivalent
Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.
A terminating nul... |
7,031,581 | 7,031,881 | search/replace boost regex C++ | I am having a regex replace issue that i can't seem to figure out for replacing some configured parameter for a file path.
Here is what I have so far:
The regex for a filepath may not be perfect but it seems to work ok.
regex: ^(?<path>[^\\/*?<>|]+)\\\\(?<filename>.+)\\.(?<ext>.mp4$)
file name match results name: $2... | Find and replace is completely unnecessary because you already have all of the components you need to build the new path.
REPLACE
std::string sz_new_file_name_path = boost::regex_replace(complete_file_name_path, old_filename, new_filename);
WITH
// path + newFileName + ext
std::string sz_new_file_name_path = rm.format... |
7,031,620 | 7,031,697 | Algorithm to simplify a path | Given a path, I want to optimize it so that all verticies that are straight on a line can be removed.
For example:
Path:
*******
* *
* *
***********
Could be optimized to:
*-----*
| \
| \
*---------*
However I want to have control over the deviation from the slope so that it doesnt have to be... | I believe that you can do this with a simple iterative walk across the points on the path. Keep track, at each point, of the last three points you've encountered. If all three of them are collinear, then remove the middle point from the path, since taking a straight-line path from the first to the third node will pas... |
7,031,621 | 7,031,838 | different values of std::floor function for arguments with same value but different types | Consider the following:
#include <iostream>
#include <cmath>
int main()
{
using std::cout;
using std::endl;
const long double be2 = std::log(2);
cout << std::log(8.0) / be2 << ", " << std::floor(std::log(8.0) / be2)
<< endl;
cout << std::log(8.0L) / be2 << ", " << std::floor(std::log(8.0L) / be2)
... | When I add this:
cout.precision(40);
I get this output:
2.999999999999999839754918906642444653698, 2
3.00000000000000010039712117215771058909, 3
You're printing two values that are very close to, but not exactly equal to, 3.0. It's the nature of std::floor that its results can differ for values that are very close t... |
7,031,842 | 7,031,889 | How do glPushMatrix() and glPopMatrix() keep the scene the same? | I found some code online which will move a box across the screen, then reset it after the box hits the end of the screen.
Here is the code:
void display(void) {
int sign = 1;
if (lastFrameTime == 0) {
/*
* sets lastFrameTime to be the number of milliseconds since
* Init() was called;
*/
lastF... | It's only the matrix, used to transform coordinates, that is restored by glPopMatrix. Not the whole framebuffer. The framebuffer contains the rendering of the quadrilateral, changing the matrix afterward doesn't affect anything already rendered.
|
7,031,870 | 7,194,374 | How can I portably implement row-wise binding of arbitrary resultsets in ODBC while avoiding alignment issues? | I have a class which takes an SQL query, executes it, then binds every column in the resultset as SQL_C_WCHAR using row-wise binding.
right now the way I do it is to allocate a vector of char, and determine the pointers to give SQLBindColumn as follows:
buffer for column 1 = &vec[0]
buffer for length indicator of colu... | The way I ended up dealing with it was to actually put the length indicators and the wchars in seperate, correctly typed, buffers. They don't actually have to live in the same buffer since all that ODBC does is add the 'struct size' to each address each time it wants to go the the next set.
I figured out the alignment ... |
7,031,909 | 7,032,016 | C++0x uniform initialization "oddity" | Like many, I am pretty excited about C++0x. I try to learn and use the new features in new projects so I can write the best, most easy-to-maintain code possible.
Needless to say, I love the idea behind the new initializers. So I'm looking at them, and these make sense to me:
T x = { 1, 2, 3 }; // like a struct or nativ... |
What's the design/thought behind this syntax?
For one thing, the brace syntax make it possible to avoid vexing parses:
T x(); // function declaration
T x{}; // value-initialized object of type 'T' named 'x'
In C++03, the closest you can get to this is T x((T())); or T x = T();, both of which require T to have an acc... |
7,031,932 | 7,031,949 | Use of #undef in C++ | I am studying a piece of code from GSL libraries and puzzled by few lines in the beginning of a header file.
I understand what #undef, #ifdef and etc. do but what I don't understand is why did they basically reset the definition of the _BEGIN_DECLS and then go on and define it again? Technically, there shouldn't be any... | You are not allowed to #define a macro that is already defined unless the parameter lists and replacement lists are identical.
If __BEGIN_DECLS was previously defined to be replaced by something other than extern "C" {, the #define __BEGIN_DECLS extern "C" { would be invalid and the program would be ill-formed.
Techn... |
7,032,050 | 7,032,073 | C++ Exception Specification for overloaded functions | class ESClass
{
public:
void PrintMe() throw();
void PrintMe(int) throw(int);
};
I want to know whether or not we can define different exception specification for overloaded functions. In other words, can we give different exception specification to different version of the function PrintMe?
Note from VS2010:... | Yes: they are different functions, they can have different exception specifications.
If a virtual member function has an exception specification, any override (not overload) must have an exception specification that is at least as strict as the member function being overridden.
Of course, you should "never write an ex... |
7,032,080 | 7,033,590 | sizeof and pass-by-reference | I am hoping that someone can explain the following behaviour.
Suppose I am trying to implement a function which determines the length of any array, but want to avoid using macros. For e.g
#define array_length(x) ( sizeof(x) / sizeof(x[0]) )
Given that the function must work with any parameter type, I must use templat... | Let's consider two function templates:
template <typename T> void f(T);
template <typename T> void g(T const&);
And let's say we have an array:
int a[10];
What happens when we call f(a);? Since we don't explicitly provide an argument to the template, argument deduction kicks in and the compiler tries to figure out w... |
7,032,162 | 7,032,196 | which C++ Compiler complies with the latest C++ standard most | I have been looking for a c++ compiler that is available and complies most with the latest C++ standard.
The latest VS2010 is good but as many said it still doesn't comply with all of the C++ standard.
| you may be interested in this summary table
EDIT:
I have found the list of tables created by Scott Meyers
|
7,032,274 | 7,032,316 | invalid conversion from ‘int (*)(int)’ to ‘int’ error? | I am learning C++ and one of the programs was for a random number generator.
Once I wrote the program I got the following errors:
dice.cpp: In function ‘int main()’:
dice.cpp:18: error: pointer to a function used in arithmetic
dice.cpp:18: error: invalid conversion from ‘int (*)(int)’ to ‘int’
Here is my code:
#inclu... | I believe that your problem is this line:
r=randn+1;
I believe that you meant to write
r = randn(/* some argument */) + 1; // Note parentheses after randn
The issue is that you're trying to call the function but forgetting to put in the parentheses indicating that you're making the call. Since you're trying to roll ... |
7,032,551 | 7,165,972 | What makes this header file slow VS2005 to a crawl? (IntelliSense exonerated?) | I was experimenting with a C++ project using the Compile Time Hashing technique I found here. The macros work as expected, and the compile time is reasonable, but the 64 recursive macros seem to being playing hell with Visual Studio's Intellisense. After every short edit, the IDE hangs for ~30 seconds. I suspect tha... | I was correct that something was getting hung up on the recursive macros, but it wasn't IntelliSense. The culprit turned out to be the free version of Refactor! for C++ from DevExpress that I had installed a long while ago (and rarely used).
When I uninstalled that, IDE performance returned to normal. I re-enabled Int... |
7,032,687 | 7,032,903 | Remove rct1 macro from codebase in microsoft visual studio 10 | I'm porting an application from Linux to Windows, and one of my variables, 'rct1', seems to clash with a macro that is coming from somewhere in Windows. I can't find any information on this - is there a way to disable this macro being defined?
| It's in Dlgs.h in the Windows SDK.
So add #define WIN32_LEAN_AND_MEAN before all #include <windows.h> so you don't bring in Dlgs.h.
|
7,032,709 | 7,032,747 | Linking two .cpp and a .h files | I'm doing an exercise (from the third chapter of Thinking in C++) but I have a problem linking two .cpp files.
This is the exercise:
Create a header file (with an extension of ‘.h’). In this file,
declare a group of functions by varying the argument lists
and return values from among the following: void, char,
int, a... | It sounds like the file is not finding the functions appropriately. Is the header file included in both files? You can include it like:
#include "myheader.h"
Did you make sure to compile both files together? Such as:
gcc -o myprogram file1.cpp file2.cpp
|
7,032,743 | 73,612,055 | Can C++'s operator[] take more than one argument? | Is it possible to define an overloaded operator[] that takes more than one argument? That is, can I define operator[] as follows:
//In some class
double operator[](const int a, const int b){
return big_array[a+offset*b];}
and later use it like this?
double b=some_obj[7,3];
| Prior to C++23 it isn't possible. You can do this from C++23.
From cppreference:
Since C++23, operator[] can take more than one subscripts. For example, an operator[] of a 3D array class declared as T& operator[](std::size_t x, std::size_t y, std::size_t z); can directly access the elements.
example code from there: ... |
7,032,766 | 7,033,009 | C++: partial function specialization for void not allowed - alternative solution? | I think I understand by now why partial function templates are considered confusing and unnecessary, and are thus not allowed by the C++ standard. I would however appreciate some help with re-phrasing the following function w/o partial specialization. FWIW, the function is a member of a non-specialized class:
templat... | First,
template <typename IMPL, typename RET>
RET call (functor <IMPL> func,
IMPL * impl)
{
return func.call (impl);
}
should really be
template <typename RET, typename IMPL>
RET call (functor <IMPL> func,
IMPL * impl)
{
return func.call (impl);
}
(I inversed RET and IMPL in the template a... |
7,033,148 | 7,033,172 | Question about object initialization semantics | I've been wondering about the language in the C++03 specification surrounding object initialization, specifically section 8.5 paragraph 9 which states,
"If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or
array thereof), the object shall be default-initiali... | Your POD_class is in fact not a POD class. A POD class cannot have a user-declared constructor.
|
7,033,267 | 8,821,487 | How do you overload templated function (specialized) in child class? | I have a base class with a templated function that has the general templated type, as well as specialized version.
#ifndef BASE_CLASS
#define BASE_CLASS
#include <iostream>
using namespace std;
struct Type1
{
};
struct Type2
{
};
class baseClass
{
public:
template<class Type>
void doStuff(Type & t)
... | The reason why it still doesn't work the way you wanted to is that the function is not virtual in the parent class. However, it is not possible to have a virtual template function.
I see two main options:
as rhalbersma suggested, make the class itself template and then override the desired method s (which now are NOT ... |
7,033,356 | 7,033,419 | Is it possible to hook the creation of windows globally so I can control where the windows are placed on the screen? | I can inject a hook into running processes to catch when they create, destroy, max/min. But I haven't come up with a way to catch the creation of a new process so that I can inject my hook into that one.
Does anyone know the best way to accomplish this?
| SetWindowsHookEx is your easiest solution.
If you don't mind upsetting the anti-virus software, you can also inject a DLL into each process that will then hook CreateProcess (to inject the DLL into further processes) and CreateWindowEx (for your purposes).
EDIT: I just read your question completely. Yes, you'll want to... |
7,033,375 | 7,033,435 | Convention for passing BSTRs into COM functions from C# (COM interop) | I am writing writing an API in COM in C++, and also writing a program which consumes this API in C#. My question is about BSTR memory management semantics when passing BSTRs into COM functions. Say my IDL looks like:
HRESULT SomeFunction([in] BSTR input);
Currently this function is implemented like this:
HRESULT SomeF... | From Allocating and Releasing Memory for a BSTR:
When you call into a function that expects a BSTR argument, you
must allocate the memory for the BSTR before the call and
release it afterwards. ...
So don't free it if it is an input parameter. C# (and any other runtime that uses COM objects) must respect the COM ... |
7,033,407 | 7,033,463 | very weird hang at a for loop initialization | I have a very weird bug that I can't seem to figure out. I have narrowed it down to a small section of code (unless the compiler is reordering my statements, which I don't believe is true).
...
std::cout << "here"<< std::endl;
std::vector<int>::iterator n_iter;
std::vector<int>::iterator l_iter;
std::cout << "here?" <... | The first thing you should try is to output std::endl after each string. This flushes the buffer for the output.
|
7,033,466 | 7,036,154 | subarray through index: how to? | I am trying to implement a simple matlab-like array (now only one dimension actually), what I tried to do is to implement the following matlab codes:
a=1:10;
ind=find(a>5);
a[ind]=5;
I know that the std has valarray to do this through a slice array. I do not know much details on it. The code is:
#include <iostream>
us... | Andrea, Thank you for the hint. Mostly what you said makes sense and really helps. I create another ind_array and keep the original array's address and now it works!
The only change is the operator[] now returns the ind_array. and the operator= for ind_array is defined to do the real assignment. (to make it simple, I ... |
7,033,516 | 7,033,897 | When should I delete object files before compiling? | In compile scripts I generally see a call to always delete object files before compiling. Does this slow down the build process? Is it really necessary with compilers that check if the object files are out of date when deciding to recompile them?
| In some way, deleting existing object files defeats the purpose of having separate translation units in the first place. Your standard build environment should normally only rebuild those object files which are older than the corresponding source file. (You don't need to delete, you can just overwrite.)
If you have a d... |
7,033,645 | 7,034,028 | Is there a generic way to adapt a function template to be a polymorphic function object? | I have some function templates, for example
template <typename T>
void foo(T);
template <typename T>
void bar(T);
// others
and I need to pass each one to an algorithm that will call it with various types, e.g.
template <typename F>
void some_algorithm(F f)
{
// call f with argument of type int
// call f wit... | The short version of the problem is given an overloaded name f, how to concisely write an object ff such that ff(a0, a1, a2, ...) ultimately calls f(a0, a1, a2, ...).
A polymorphic functor, how you point out yourself, is the usual solution. But it must be defined out of line (since it has a template member), so I'll co... |
7,033,649 | 7,033,677 | C++ class with static pointer | I don't understand pointers and references very well yet, but I have a class with static methods and variables that will be referenced from main and other classes. I have a variable defined in main() that I want to pass to a variable in this class with static functions. I want those functions to change the value of the... | Provide the definition of the static variable outside the class as:
//foo.h
class foo
{
public:
static int *myPtr; //its just a declaration, not a definition!
bool somfunction() {
*myPtr = 1;
//where is return statement?
}
}; //<------------- you also forgot the semicolon
//////////... |
7,033,855 | 7,071,802 | MSVC10 /MP builds not multicore across folders in a project | I'm hoping someone points out something wrong or a workaround for what we are experiencing.
When compiling a project with /MP it appears that only files in the same folder are compiled concurrently. I used process explorer to swipe the command line and confirm the behavior.
Project filters seem to have all no impact o... | The use of %(RelativeDir) in "Object File Name" ( in the vcxproj XML, /Fo on the CL.exe command line ) project causes msbuild to batch the cpp files to cl.exe on a per directory basis. This can have a significant impact on the benefits gained from using /MP.
Note that if your project uses %(RelativeDir) for object fi... |
7,034,297 | 7,034,414 | Global function template overloading and const parameters | If I compile (gcc 4.6.0) and run this code:
#include <iostream>
template <typename T> void F(/* const */ T& value) {
std::cout << "T & " << value << std::endl;
}
template <typename T> void F(/* const */ T* value) {
std::cout << "T * " << value << std::endl;
F(*value);
}
int main(int argc, char* argv[]) {... | During overload resolution, overloads requiring no conversions beat overloads requiring some conversions, even if those conversions are trivial. Quoting the C++03 standard, [over.match.best] (§13.3.3/1):
Define ICSi(F) as follows:
if F is a static member function, ICS1(F) is defined such that ICS1(F) is neither bette... |
7,034,299 | 7,047,841 | libs suddenly won't load in dynamic linker (NDK) | I've been developing an NDK app for quite some time and it's been working well. However, today the app randomly decided to not start anymore, after I compiled it after making some nominal change. It's caused by a cryptic problem with loading the app's main library. Here's some log output:
08-11 18:38:11.220 D/dalvikvm(... | I ended up compiling everything with a fresh NDK install, and it worked. It's as if the old one was corrupted somehow, though I have no idea how.
It was also an upgrade from r5b to r6, so maybe it's related to the NDK version.
|
7,034,300 | 7,034,323 | weak_ptr's weird copy constructors | the following are 2 of weak_ptr's constructors:
http://msdn.microsoft.com/en-us/library/bb982126.aspx
weak_ptr(const weak_ptr&);
template<class Other>
weak_ptr(const weak_ptr<Other>&);
actual code (from memory):
weak_ptr(const weak_ptr& _Other)
{ // construct weak_ptr object for resource pointed to by _Other
t... | Q1) If you don't write a copy constructor, the compiler will generate one for you, which wouldn't be what you want. Templated conversion constructors don't count.
Q2) Remember that shared_ptr<T> is like a T*, convertibility must be checked at the level of pointers. If T* is convertible to U* then you should be able to ... |
7,034,312 | 7,034,625 | Visual C++ project developed in Visual C++ 2005 - In Visual C++ 2010, debug assertion fails on menu open, but release mode works, how to fix? | I just started working on a project that was developed in Visual C++ 2005 using MFC, by someone else. To do so, I installed Visual C++ 2010 - I have no experience using either version (or visual studio at all, for that matter).
The application has a menu bar that is implemented using the CMenu class, and is initialized... | According to MSDN (http://msdn.microsoft.com/en-us/library/177ay1x0.aspx)
CMenu::LoadMenu() requires a parameter to be passed in, which is missing in your sample code.
Do check on that and make sure you are passing a valid menu resource id.
Edit:
Your menu object is constructed on the stack and will be destroyed once i... |
7,034,592 | 7,034,726 | Create BSOD from user mode? | I was getting bored with my XP box one day, so I decided to try some of the answers to this question to see if any of them would cause a BSOD.
They didn't, and they seemed like they would be the most likely to do that, so I was wondering if it is possible to trigger a BSOD from user-mode in C/C++, and if so, how?
| It seriously difficult to make a BSOD from user mode unless the user mode program interacts with buggy drivers (may be a particular sequence of operations can reveal the bugs in particular driver) disturbs the driver stack. From user mode, the inputs are validated well before passing to the kernel mode to ensure the st... |
7,034,633 | 7,034,750 | Using a typename nested in a template parameter | This is a mouthful, so here's a piece of code as an example:
template<typename T>
void foo(const T& a, typename T::value_type::value_type b) { }
std::vector<std::vector<int>> vec;
foo(vec, 4); // Error, can't specialize function template
This compiles and runs correctly using gcc. It doesn't compile using Visual Stud... | This is absolutely a deficiency on VC++ 2010's part – std::vector<int>::value_type is a type, not a template, and should not be decorated as such. In fact, use of that syntax in this context should cause a compiler error.
Supporting evidence is that the following does compile (as it should):
#include <vector>
template... |
7,034,658 | 7,034,929 | assigning ASCII values to variables in bison | I want my parser to handle case like:
a='A'; // a should be set with ASCII(A) i.e 65
My token declaration looks like :
%union {
double dval;
char *symbol;
}
%token <symbol> SYMBOL_NAME
%token <dval> NUMBER
%token BINARY
%token OCTAL
%token DECIMAL
%token HEXADECIMAL
%token UNSIGNED
%token <symbol>CHAR
%token SHO... |
what is incorrect here?
The answer almost certainly lies in the flex side of your parser: It is never returning a CHAR token.
You haven't shown us the flex side of your parser, but how are you making flex distinguish between a SYMBOL_NAME and a CHAR? Typically the code that detects a <single_quote> <char> <single_quo... |
7,034,662 | 7,035,905 | Custom client app - need ability to control where documents are saved | Okay SO. I need some guidance. I apologize for the length of this post, but I need to provide some details:
I've got someone who is interested in me to do a small project for them. The application in general is a fairly straightforward employee record keeping / documentation app, but it makes pretty heavy use templa... | Word does allow for programming some "Save" and "Save As" control via its object model. Any subroutines coded in VBA and placed into your Word template will be copied into all documents generated from that template. Additionally, most menu and Ribbon commands can be intercepted by creating a module containing subroutin... |
7,035,023 | 7,035,078 | std::max - expected an identifier | I'm having a problem with std::max. I can't figure it out.
int border = 35;
int myInt = 2;
int myOtherInt = 3;
int z = std::max(myInt + 2 * border, myOtherInt + 2 * border);
I've included the algorithm standard header. When I mouse over max, I am getting:
Error: expected an identifier
And a compile errors of:
error... | Hazarding a guess, since you're using VC++ – put this before any #includes:
#define NOMINMAX
windows.h defines macros named min and max like so:
#define min(a,b) (((a) < (b)) ? (a) : (b))
#define max(a,b) (((a) > (b)) ? (a) : (b))
The Windows SDK has contained these macros since before C++ was s... |
7,035,048 | 7,035,126 | how to convert string in integer numbers | I am receiving string such as "2011-08-12,02:06:30" from the server which specifies data and time.
But how to convert it into int and store like
int year = 2011, month =08, day = 14, h = 02, min = 06, sec=30.
| You can use stringstream class in C++.
#include <iostream>
// for use of class stringstream
#include <sstream>
using namespace std;
int main()
{
string str = "2011-08-12,02:06:30";
stringstream ss(str);
int year, month, day, h, min, sec;
ss >> year;
ss.ignore(str.length(), '-');
ss >> month;
ss.... |
7,035,294 | 7,035,310 | C++ Communication via COM Port | How can one communicate with a device via a COM port with C++? Is there a windows library which handles this?
Thanks in advance.
EDIT: Im using Windows.
| A lot of sample code on the web if you Google. Here's one example: http://members.ee.net/brey/Serial.pdf
|
7,035,356 | 7,035,382 | C++ - Why static member function can't be created with 'const' qualifier | Today I got a problem. I am in the need of a static member function, const is not a must but a better. But, I didn't succeed in my efforts. Can anybody say why or how?
| When you apply the const qualifier to a nonstatic member function, it affects the this pointer. For a const-qualified member function of class C, the this pointer is of type C const*, whereas for a member function that is not const-qualified, the this pointer is of type C*.
A static member function does not have a thi... |
7,035,362 | 7,035,412 | C++ usage extern in front of function | I have seen an interview question from Bloomberg from here: http://www.careercup.com/question?id=383154
extern void print(int *a, int z);
void print(int *a, int z);
Question 1> Will it compile?
Question 2> If it compiles, what does it mean?
extern int i;
int i;
Question 3> Will it compile?
Question 4> If it compiles,... | // a function declaration
extern void print(int *a, int z);
// still a function declaration
void print(int *a, int z);
Answer 1
Yes, it compiles successfully.
Answer 2
A global function without a body {} is automatically a function declaration. The keyword extern is optional. So both of them are just declarations. And... |
7,035,410 | 7,035,476 | Optimizing / simplifying a path where many points are close together? | I have a path of points that represent the outline of a polygon. The path is constructed from pixels.
This means all points are very very close to each other, but I've ensured they are all unique.
Right now I'm checking if 3 points are collinear, and if they are, I remove the middle one.
I check if they are collinear u... | You want the 2x2 determinant vec1.x * vec2.y - vec1.y * vec2.x instead of the dot product. The determinant is zero iff the points are collinear, whereas the dot product is zero iff the points form a right angle.
|
7,035,462 | 7,035,499 | what happens for virtual function that is non-public inherited by subclass? | I have seen this question http://www.careercup.com/question?id=384062
class Base {
public :
virtual void method () = 0;
private :
int n;
};
void Base::method() { n = 1;}
class D1 : Base {};
class D2 : public D1 {
int i;
void method() {i = 2;}
};
It passed the compiler of vs2008 and g++ 4.4.3
Here is... | D1 has inherited variable Base::n but it cannot access it.
Correct.
Private members of a class are never accessible from anywhere except the members of the same class.
D1 has inherited the function Base::method but it doesn't call/modify this inherited function in the above implementation.
Correct, but conditonally, ... |
7,035,503 | 7,036,032 | what is the best way to initialize my global data in shared library? | I have a single class which does all the required initialization.
currently i have declared a global object of this class type, which is being instantiated on library load.
I've seen other ways, like delaring
BOOL APIENTRY DllMain
entry point for the shared library, and does the actual initialization on process attac... | This is what happens during C++ DLL startup:
System calls DLL's entry point, generated by you compiler
Entry point calls DllMainCRTStartup (name may differ), which initializes C/C++ runtimes and instantiates all global objects.
DllMainCRTStartup then calls user-defined DllMain.
I personally prefer DllMain, because th... |
7,035,621 | 7,035,814 | Boost RegEx: Specific Question | I am trying to use this expression:
Expression: "\w{1,}\s*?\-\-(\>)?\s*?\w{1,}"
Keep in mind I am escaping the \ with a second \ in my code.
When searching in the strings below. I think I am close, but no cigar. I want the expression above to be able to find matches in the text below. Where am I going wrong?
Text: ... | Not sure if i understood your question correctly, but if you want your regex to match for example AB and CD in "AB --> CD" you can use the following regex:
Expression: "(\w+)\s*-->?\s*(\w+)"
|
7,035,735 | 7,035,893 | How to return a reference to a variable in C++? | I have a C++ static class with a method that creates an object. I would like to retrieve the object created by this method in a different function so that this new function takes ownership of the object. This is the code I have so far:
MessageBoxes.h
class MessageBoxes {
public:
static int info(const QString& mes... | 0) We don't do this "static class" thing in C++. Those are hacks to deal with the fact that Java and C# force you to put all your code into classes. C++ does not do that, so we shouldn't hack around a limitation that doesn't exist. Classes are not storage places for code; they exist to define a data type. What you're r... |
7,035,782 | 7,035,844 | Can someone tell me what this crazy c++ statement means in C#? | First off, no I am not a student...just a C# guy porting a C++ library.
What do these two crazy lines mean? What are they equivalent to in C#? I'm mostly concerned with the size_t and sizeof. Not concerned about static_cast or assert..I know how to deal with those.
size_t Index = static_cast<size_t>((y - 1620) / 2);
as... | size_t is a typedef for an unsigned integer type. It is used for sizes of things, and may be 32 or 64 bits in size. The particular size of a size_t is implementation defined, but it is unsigned.
I suppose in C# you could use a 64-bit unsigned integer type.
All sizeof does is return the size in bytes of a C++ type. Ever... |
7,035,793 | 7,035,801 | C++ reference pointing to a temporary variable? | class ClassB {
int m_b;
public:
ClassB(int b) : m_b(b) {}
void PrintClassB() const {
cout << "m_b: " << m_b << endl;
}
};
int main(int argc, char* argv[])
{
const ClassB &af = ClassB(1);
af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3
}
Given the above code, I have difficult... | const ClassB &af = ClassB(1);
const here extend the life time of the temporary object (i.e., ClassB(1)) being created. It's scope lasts until af falls out of scope;
af.PrintClassB(); // print m_b: 1 with vs2008 & gcc 4.4.3
This is because, af is nothing but the temporary object's reference which was constructed passi... |
7,036,158 | 7,036,221 | Can't get past "undefined reference to `XXXX'" | I'm currently writing a header-only wrapper library which is supposed to provide C++ access to some FORTRAN code. But I'm stuck at the 'undefined reference (...)'
I must say I'm a little bit surprised because I compiled my own functions in C++ using this FORTRAN routine, with no problems at all.
Maybe a few words about... | The order in which you specify libraries in GCC's command-line matters. Read GCC man pages for details - in short you have to specify libraries (-lnest3 etc) after modules that use them. (I always specify libraries in the end of the command-line.)
In your case you have to write
gfortran ExampleLibMnCpp.o -o ExampleLibM... |
7,036,334 | 7,036,503 | an STL set of custom objects, each containing an STL set | As is hopefully clear from the code below, I'd like to have a set of objects objectSet, each containing str1 and str2. The set is keyed on str1, and any new objects with an str1 already in the objectSet will not be added, but if this new object has a different str2, I want to keep track of the fact that I saw it in th... | Your design is flawed. You are using Object as a key to a set, but then you are attempting to modify the keys of your set. Of course you are only modifying parts of Object that don't affect it's use as a key, but the compiler doesn't know that. You need to modify your design, your second version is fine to me, I wouldn... |
7,036,393 | 7,036,496 | Replacing table name with a variable in a query | i have the following code.My table is called 'tableu'.I want replace 'tableu' with a variable that will hold the table name. How can i represent that.
query.prepare(
"INSERT INTO tableu (village, weight, diet, age)"
"VALUES (:village, :weight, :diet, :age)"
);
| If you want to change your table name from tableu to lets say NewTableName, it can be done using any of the following syntax:
query.prepare(
"RENAME tableu TO NewTableName"
);
OR
query.prepare(
"ALTER TABLE tableu RENAME TO NewTableName"
);
Update:
May be the OP i... |
7,036,601 | 7,036,853 | Compiler independent C++ properties | Microsoft Visual C++ compiler has the property declaration construction
__declspec( property( get=get_func_name, put=put_func_name ) )
Is there a compiler independent version of Microsoft C++ __declspec(property(...)) or another analogs?
| No.
As usual, an identifier preceded by __ is reserved to the compiler. In C++03 you have __cpluscplus (to identify C++ vs C), __FILE__ and __LINE__. All those are preprocessor entities.
In C++0x, the difference is blurred by the introduction of the __attribute__ word which is the first I know of that has semantics val... |
7,037,092 | 7,037,126 | template and executable file | Is it true that template code compiled and linked into a PE will increase in size compared to code without templates. I think each instances of templates used is packed orderly so it will output a match if required faster.
Sorry for the question I just don't know much about template.
| C++ works on the principle:
You pay for what you use.
Template code creates binaries only for the code that you use/Instantiate.
Just because you compile against Standard Library which has hundreds of STL containers it does not mean your object code includes all of them, It only includes the ones you use.
Templates im... |
7,037,249 | 7,037,601 | On what bases the size and range of any datatype is decided? | I what to know that what is the base on which the size of any datatype is decided. For eg. size of intger datatype in java is 4 bytes. So why its exactly 4 and not anything else. More over maximum number that can be stored with int type is 2,147,483,648. When this number come from? I mean what is the formula to get thi... | In assembler size in bits of the types is defined by the architecture that has to work with the numbers. Most current architectures group bits in 8-bit bytes, and double the size of the number when going to the next type: 8, 16, 32, 64, 128... but not all architectures support all the types, and some old architectures ... |
7,037,255 | 7,037,671 | Detect Screen Rotation in Qt issues | I want to do some changes on screen rotation , the code of the method that is supposed to handle such event is taken from here
http://www.developer.nokia.com/Community/Wiki/CS001437_-_Listening_for_screen_orientation_changes_in_Qt
edit: I have a scroll area , and its getting of border on rotation how can i adjust its s... | I do not see any reference to your QMyWidget class other than the below line. May be I'm missing something. But if you have defined your QMyWidget class elsewhere, you atleast need to include the header.
void QMyWidget::resizeEvent(QResizeEvent* event)
{
ui->labelk->setText("blabla");
}
May be you meant this inste... |
7,037,305 | 7,037,328 | "Cleared" Are Macros exported to a .lib file? | I have some macros like, #define dosomething(x) something(x) and it is compiled into a dll. Will I have that macro in that lib created by the build?
| No.
Macros aren't even visible to the compiler. They get replaced by their substitution text during preprocessing, which happens at the very beginning. Macros are dumb, they know nothing about you or your motives. They don't even know what language you're writing. Beware!
|
7,037,596 | 7,044,430 | Animated graphics implementation dialog based MFC | Could anyone suggest me a particular way to implement animation in my Dialog-based mfc program? The animation that I am intending to add is like a construction digger machine graphic that would read the values of the machine parameters and change the shape of the graphic accordingly. Most of the information is read fro... | Well, GDI is easy but ugly and quite slow, GDI+ is also easy, but nicer although generally slower. OpenGL or DirectX are much, much faster but quite hard to program. Other libraries, such as cairo, are also available.
I'd suggest to start with the easiest (maybe GDI+) and see if it is fast enough for you.
Do do that, j... |
7,037,675 | 7,041,415 | Anyone used the MATLAB tool to produce C/C++ code? Is the resulting code viable for production use? | We have some researchers who do a lot of work in MATLAB. We often would love to try their code as part of a bigger workflow that requies the algorithms to be put into C/C++ or Python. I've seen MathWorks advertise a tool to create native C or C++ code. How good is the code? Does it support the toolboxes? I'd still see ... | I have worked with mathworks extensively in the past on this. The toolboxes are expensive, but the support is outstanding. We benchmarked code generated for a specific DSP and it was within 10% the speed of hand generated code, and took a fraction of the time to generate. Mathworks has been investing heavily in thes... |
7,037,680 | 7,037,812 | How to check if the casting to wchar_t "failed" | I have a code that does something like this:
char16_t msg[256]={0};
//...
wstring wstr;
for (int i =0;i<len;++i)
{
if((unsigned short)msg[i]!=167)
wstr.push_back((wchar_t) msg[i]);
else
wstr.append(L"_<?>_");
}
as you can see it uses some rather ugly hardcodi... | Doesn't work like that. wchar_t and char16_t are both integer types in C++. Casting from one to the other follows the usual rules for integer conversions, it does not attempt to convert between charsets in any way, or verify that anything is a genuine unicode code point.
Any replacement characters will have to come fro... |
7,037,753 | 7,037,805 | How much interoperability is there between C++ and Scala? | Everybody knows about Java and Scala, but how much interoperability is there between C++ and Scala. Can classes from one be be used by the other, for example?
| It's not that simple at all. Java and Scala work on the same virtual machine and scala has been designed to work well with java.
C++ generates native code, and even each compiler has its own way to generate that native code. That means that some class compiled with Visual Studio won't interact easily with another class... |
7,037,838 | 7,038,001 | Can somebody suggest me c++ library for serial port communicaiton which works on x86 and x86_64 versions of OS? | Can somebody suggest me c++ library for serial port communicaiton which works on x86 and x86_64 versions of OS ? I have used Java SerialIO but it crashed on x86_64 versions.
| If you want c++ then QextSerialPort is your choise.
|
7,037,846 | 7,056,294 | Drag and Drop functionality in my graphic - Dialog Based MFC | I have a dialog based MFC application that reads the coordinates of height and radius from a text file and displays it as a plot of points on a picture control window. Now, after the points have been plotted I need to be able to drag and drop a point to any particular location in the window in order for me to have the ... | Several things for drag & drop:
In OnRButtonDown(), you need to identify the point you'd pick up, set the RButtonDown flag to true.
Check the flag and if true, post paint message to draw the plot dynamically per the new position of the point in OnMouseMove(), to make it as smooth as possible (not flashing), do not inv... |
7,037,854 | 7,038,270 | Install third party libraries on Mac OS X? | I want to install some great third-party libraries on Mac OS X which will be used in Objective-C for some iOS programs :)
Since I am just a beginner of Mac OS X and Objective-C, I am not so sure about the installation process. I just tried to install the libraries by compiling the source codes (simple operations like .... | The problem is that you need root permission to install in the regular install directories. Try this:
sudo make install
sudo executes the command as root, which means it can do whatever it needs to. You'll have to enter your password, and it won't echo the letters (or even asterisks) as you type them for security. Gen... |
7,037,879 | 7,039,302 | How to detect the one function causing a stack overflow quickly in Visual C++? | I have a huge C++ codebase. On a certain set of data there's a stack overflow. If I run the program under Visual Studio debugger I get a call stack 30 unfamiliar functions deep - one (or more) of those functions created a too big object on stack and this lead to stack exhaustion. I looked at all functions and there's n... | You can use Code Analysis in Visual C++ which is available in higher editions. A warning (C6262) is generated if function uses stack higher than some limit. You may use /analyze:stacksize switch, where stacksize is limit you want.
|
7,037,933 | 7,040,387 | ShellExecute crashes | I have a program which crashes on the ShellExecute() instruction. If I use the method system(), all works fine but I have read that system() was evil...
I'm using Visual Studio 2010 SP1.
So there is my function which calls ShellExecute:
ATC_GENERIC_API void __cdecl atcGenericLaunchGAG()
{
HINSTANCE ret = ShellExecu... | As Cory Nelson said, the error is not in the API itself, but in MFC. There might be a ShellExecute hook that causes your application to crash.
|
7,038,357 | 9,657,991 | make_unique and perfect forwarding | Why is there no std::make_unique function template in the standard C++11 library? I find
std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3));
a bit verbose. Wouldn't the following be much nicer?
auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3);
This hides the new nicely and only mentions t... | Herb Sutter, chair of the C++ standardization committee, writes on his blog:
That C++11 doesn’t include make_unique is partly an oversight, and it will almost certainly be added in the future.
He also gives an implementation that is identical with the one given by the OP.
Edit: std::make_unique now is part of C++14.
|
7,038,405 | 7,039,066 | Drop-in replacement for MICO Corba? | We are currently using MICO to establish the communication between a server and a client, where the client is a simulator written in C++ and the server is a java program displaying an animation of what happens in the simulation. It seems that the developemt of MICO has slowed down to an almost halt and bugs that only a... | I don't know where CORBA or MICO in particular has gone in the last 5 years, but back then a drop in replacement was not really possible, since differences between vendors where still there.
Not necessarily API differences (POA, etc.) but
in implementation behavior,
in custom extensions which were required to make i... |
7,038,432 | 7,038,565 | What does UNDEF and notype() mean when seeing the C++ library information using dumpbin? | I used dumpbin /symbols to see the library I created. Some functions have UNDEF notype in the output. What does that mean? Is there any link to study the structure of dumpbin output?
| We can take a look at the MSDN documentation for dumpbin /SYMBOLS:
This option displays the COFF symbol table. Symbol tables exist in all
object files. A COFF symbol table appears in an image file only if it
is linked with /DEBUG.
The following is a description of the output for /SYMBOLS. Additional
information ... |
7,038,581 | 7,039,232 | Why do we need a priority queue in Prim's Algorithm | As my question speaks I want to know why do we use Priority queue in Prim's Algorithm?
How does it saves us from using the naive way (yes I've heard of it but don't know why).
I'd be very happy if anyone could explain step by step for adjacency list . I am using Cormen's book.
The pseudocode :
Prim(G,w,r) //what is w (... | In prim's algorithm, there is a step where you have to get the 'nearest' vertex. This step would cost O(N) if using normal array, but it'd take only O(logN) if you use priority queue (heap for example)
Hence, the reason for using priority queue is to reduce the algorithm's time complexity (which mean it make your progr... |
7,038,763 | 7,047,511 | How to debug QDomElement in QtXml? | I've got a QDomElement, and I would like to debug it, i.e. see it as plain text in debug console. In order to output it with qDebug(), it needs to be in QString format, however I don't see any conversion method from a QDomElement nor a QDomNode.
Any idea? Thanks!
| There is no built-in operator for streaming DOM elements to QDebug. You could write one easily enough, something like:
QDebug operator<<(QDebug dbg, const QDomNode& node)
{
QString s;
QTextStream str(&s, QIODevice::WriteOnly);
node.save(str, 2);
dbg << qPrintable(s);
return dbg;
}
|
7,038,797 | 7,039,832 | Automatically pick a variable type big enough to hold a specified number | Is there any way in C++ define a type that is big enough to hold at most a specific number, presumably using some clever template code. For example I want to be able to write :-
Integer<10000>::type dataItem;
And have that type resolve to the smallest type that is big enough to hold the specified value?
Background: I ... | Boost.Integer already has facilities for Integer Type Selection:
boost::int_max_value_t<V>::least
The smallest, built-in, signed integral type that can hold all the values in the inclusive range 0 - V. The parameter should be a positive number.
boost::uint_value_t<V>::least
The smallest, built-in, unsigned integr... |
7,039,006 | 7,039,171 | How to implement safe copy constructor for class that has internal placement new (with std::string) | Here's my code:
struct RS_Token
{
char id;
char cleanup;
unsigned char array[sizeof (std::string) > sizeof (double) ? sizeof (std::string) : sizeof (double)];
RS_Token(int a) :
id(a),
cleanup(0)
{
}
RS_Token(int a, const char* pstr) : // identifier or text
id(a),
... | I'm not sure that what you're doing is at all a good design, but to answer your question about placement-new: You provide the constructor arguments just like in any other new expression:
Construct new string:
typedef std::basic_string<unsigned char> ustring;
RS_Token(const char* pstr)
{
void * p = static_cast<void*>... |
7,039,055 | 7,039,293 | How can we Implement a c++ class such that it allows us to add data members at runtime | How can we Implement a c++ class such that it allows us to add data members at runtime. This question was asked in an interview.
| I find that to be a quite interesting interview question. If I was asking it, I would hope for that to be a starter of a back and forth conversation. The interviewed would have to know that you cannot add members dynamically, but I would hope for questions about the actual problem to solve (what do you want to solve? w... |
7,039,176 | 8,009,101 | What is the native way to communicate with a standard USB PTP/MTP camera on Windows? | I'm looking at WinUsb, and I have a feeling it's not what I need. Could you please point me in the right direction?
I just need to detect device and send/receive raw data. I used to use libusb, but some of it's characteristic force me to switch to a native API. The only problem is I don't know it's name.
| I've got some answers here:
https://sourceforge.net/mailarchive/forum.php?thread_name=HKEDKEEGPPEOHLHHEPEDKEOADBAA.michael.plante%40gmail.com&forum_name=libusb-win32-devel
In a few words - WPD for Windows Vista/7 and ReadFile/WriteFile for XP.
|
7,039,189 | 7,042,452 | Which openMP pragma do I use for a blocking for loop? | My algorithm (solving Poisson's equation) is completely parallelizable--provided that all the threads sync at the end of each iteration.
Function f, fNext;
init(f);
#pragma omp parallel
for(int step=0; step<maxITER; step++) {
#pragma omp for
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
fNext(i,j... | Yes. From the OpenMP Spec (eg, v 3.1, but this has been in since the beginning), under "worksharing constructs:"
There is an implicit barrier at the end of a loop construct unless
a nowait clause is specified.
That is, at the end of the for loop, unless you do something like #pragma omp for nowait, there is an im... |
7,039,266 | 7,039,280 | const definition doubts | Does it make any difference to define something as
const string msg=_T("serious");
const string& msg=_T("serious");
and
string const msg=_T("serious");
string const&msg=_T("serious");
Thank you
| There is No difference both of them are same. It is just different style of saying so.
|
7,039,304 | 7,039,357 | "Invalid initialization" error when reading from a map | I'm getting the following error when trying to build:
error: invalid initialization of non-const reference of type "std::vector<......"
Code:
class Config {
public:
std::vector<string>& GetValuesForList(std::string listName);
private:
std::map<std::string, std::vector<string> > lists;
};
... | map::find returns iterator. So you should use it's second value:
inline std::vector<string>&
Config::GetValuesForList(std::string listName) {
return lists.find(listName)->second;
}
|
7,039,324 | 7,039,344 | Warning C4172: Returning a reference to const std::string bound to a local variable. How safe is it? | I was just building one of our projects at work and I see a new function was added:
const std::string& ClassName::MethodName() const
{
return "";
}
The compiler gives a warning:
Warning C4172: returning address of local variable or temporary
I think the compiler is right. How safe is this function?
Note that the ... | Yes it is not safe.
Returning address of a local variable or temporary and dereferencing it results in Undefined Behavior.
As you commented:
Yes, the lifetime of the temporary bound to a constant reference increases till the lifetime of constant. But that needs the caller to accept the return value in a const reference... |
7,039,423 | 7,039,888 | Interrupt running program and save data | How to design a C/C++ program so that it can save some data after receiving interrupt signal.
I have a long running program that I might need to kill (say, by pressing Ctrl-C) before it finished running. When killed (as opposed to running to conclusion) the program should be able to save some variables to disk. I have ... | to do that, you need to make your program watch something, for example a global variable, that will tell him to stop what it is doing.
For example, supposing your long-running program execute a loop, you can do that :
g_shouldAbort = 0;
while(!finished)
{
// (do some computing)
if (g_shouldAbort)
{
// s... |
7,039,474 | 7,039,640 | Can I use (boost) bind with a function template? | Is it possible to bind arguments to a function template with (boost) bind?
// Define a template function (just a silly example)
template<typename ARG1, typename ARG2>
ARG1 FCall2Templ(ARG1 arg1, ARG2 arg2)
{
return arg1 + arg2;
}
// try to bind this template function (and call it)
...
boost::bind(FCall2Templ<int, ... | I don't think so, only because boost::bind in this case is looking for a function pointer, not a function template. When you pass in FCall2Templ<int, int>, the compiler instantiates the function and it is passed as a function pointer.
However, you can do the following using a functor
struct FCall3Templ {
template<t... |
7,039,597 | 7,039,749 | what will happen if you do "delete this;" in a member function? | What will exactly happen if a member function try to do delete this;, like in the constructor of the following class?
class A
{
public:
A(int);
~A();
int *pi;
}
A::A(int i)
{
delete this;
pi = new int(i);
}
A::~A()
{
delete pi;
}
| This C++ FAQ entry answers this quite nicely, repeating here:
As long as you're careful, it's OK for an object to delete this.
Here's how I define "careful":
You must be absolutely 100% positively sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a gl... |
7,040,076 | 7,041,294 | Name-lookup of nested classes with inheritance | Is this guaranteed to work:
struct A
{
struct Gold {};
};
struct B : public A
{
typedef Gold BaseGold;
struct Gold {};
};
struct C : public B
{
typedef Gold BaseGold;
struct Gold {};
};
static_assert(is_same<B::BaseGold, A::Gold>::value, "Not the right treasure!");
static_assert(is_same<C::BaseGold, B::Gol... | Undefined behavior.
3.3.7/1
The following rules describe the scope of names declared in classes:
2) A name N used in a class S shall refer to the same declaration in its context and when re-evaluated in the completed scope of S. No diagnostic is required for a violation of this rule.
|
7,040,310 | 7,040,590 | Problem with getline and "strange characters" | I have a strange problem,
I use
wifstream a("a.txt");
wstring line;
while (a.good()) //!a.eof() not helping
{
getline (a,line);
//...
wcout<<line<<endl;
}
and it works nicely for txt file like this
http://www.speedyshare.com/files/29833132/a.txt
(sorry for the link, but it is just 80 bytes so it sho... | The not-very-satisfying answer is that you need to imbue the input stream with a locale which understands the particular character encoding in question. If you don't know which locale to choose, you can use the empty locale.
For example (untested):
std::wifstream a("a.txt");
std::locale loc("");
a.imbue(loc);
Unfortun... |
7,040,736 | 7,040,837 | How to create a one-to-many wait mechanism in WinAPI | I have a thread that puts data in a buffer and multiple threads that will read their portions of data from the buffer.
How can I create a synchronization mechanism to satisfy those requirements:
Writer thread writes all data into buffer and lets all reader threads run at the same time (ok, i did it with Semaphore). Th... | You should use a Readers-writer lock.
In Windows there is a Slim Reader/Writer lock which I recommend that you have a look at.
|
7,040,985 | 7,335,401 | I'm getting contradictory answers, what should I do with my code? | I am making a RPG game in C++ and DirectX.
I store all the data for the game in .txt files and read/write it using `ifstream/ofstream. this has worked well for me so far when talking about creature stats and I have a hack together for creature names but this is becoming a problem.
I can store strings in the txt file ... | You can convert freely between C-style strings and C++'s std::string. Just use my_cpp_string.c_str() to get the C-string representation of a C++ string, and std::string my_cpp_string(my_c_string) to initialize a new std::string from a C-style string.
|
7,041,030 | 7,041,122 | Converting c project to a desktop application | I have created a c/c++ program which uses opencv library. I want to convert it into desktop application which can be run by simply installing it on any system. Also can it be done so that user installing software does not need opencv. I mean it comes packaged with software
How this is done and can you point to some goo... | To avoid having the user install OpenCV, you can try to link statically to its binaries. Check the OpenCV documentation, it might have instructions to do that. As for a portable GUI for C++, there are even books about that, but a popular one seems to be wxWidgets .
There is also a question about portable C++ UI toolkit... |
7,041,181 | 7,041,795 | Equivalent to cvSetImageROI in the OpenCV C++ interface | I'm migrating an old test application from the OpenCV C interface to the new C++ interface (I wish to learn it). What's the equivalent, using the C++ interface, of cvSetImageROI and cvResetImageROI? I couldn't find it in the documentation.
| Actually, it's right on the docs. Shame on me.
//Make a rectangle
Rect roi(10, 20, 100, 50);
//Point a cv::Mat header at it (no allocation is done)
Mat image_roi = image(roi)
|
7,041,350 | 7,041,378 | Can GCC compile classes to work as structs? | Is there any way to force a compiler (well GCC specifically) to make a class compile to object oriented C? Specifically what I want to achieve is to write this:
class Foo {
public:
float x, y, z;
float bar();
int other();
...etc
};
Foo f;
float result = f.bar()
int obSize = sizeof(Foo);
Yet compile to exactly... | Your compiler actually does exactly that for you. It might even be able to optimize optimistically by putting the this pointer in a register instead of pushing it onto the stack (this is at least what MSVC does on Windows), which you wouldn't be able to do with standard C calling convention.
As for:
obSize = sizeof(flo... |
7,041,662 | 9,925,439 | C++ and Java GUI linkage through SWIG | I am trying to include a computational chemistry/physics visualizer known as Avogadro (1) inside of my jTabbedPane project. I used QT Jambi (1) to create a JUI (Java GUI) out of Avogadro's UI in Eclipse. I was successful in that attempt, but the GUI was (obviously functionless) upon running.
In short, the complication... | It looks like Avogadro is open source. Therefore, you can download the source code and SWIG the entire project. This will give you the same classes in Java as you would have in C++.
If you only want a subset of Avogadro's functionality, I would suggest creating a simple bridge class in C++. This bridge class, with poss... |
7,041,886 | 7,041,958 | Will the compiler-generated destructor of an abstract base class be virtual? | class Base
{
virtual void foo() = 0;
//~Base(); <-- No destructor!
};
Obviously, Base will be derived. So, does C++ says the compiler-generated destructor of Base must be virtual?
Thanks!
| No, the destructor will not be virtual unless you mark it as such. The reason is simple - calls can be made virtually both via pointers and via references and how and whether you make calls virtually is unrelated to whether you create objects with new. If you don't create objects with new you don't have to delete them ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.