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 |
|---|---|---|---|---|
5,374,587 | 5,374,628 | I want to know which is the best 'C' compiler for Windows 7? | I'm using dev c++ but it has creating some problems while working with windows 7
So want the best compiler which is works with windows 7.
By best I mean whiich will give me the best performance.
| well, there are many to choose from:
Visual Studio, works 'best' with MS
OSes
Eclipse or Code::Blocks with
GCC, works 'best' with standard
C99 code
Pelles C works best at being simple
Your choice really boils down to what you require and what your working with, so just look at the above examples, pick what suites yo... |
5,374,677 | 5,375,263 | How to create Common log file for multi threaded application in mfc? | Is there any library file to log the details in the file and check for size limit of the file and compress the file?
| Basic search revealed log4cxx?
|
5,374,754 | 5,374,824 | Boost error conversion from ‘boost::filesystem3::path’ to non-scalar type ‘std::string | I have code:
std::string firstFile = boost::filesystem::path(first->name()).leaf();
But get error:
error conversion from ‘boost::filesystem3::path’ to non-scalar type ‘std::string
How can i fix it?
Thank you.
| std::string firstFile = boost::filesystem::path(first->name()).leaf().string();
also note that the leaf function is deprecated and is removed in Boost.Filesystem V3.
|
5,374,850 | 5,375,107 | How C++ object keeps information about its member functions | class A {
public :
void printSometext() {
std::cout << "printing A" << std::endl;
}
};
class B {
public :
void printSometext() {
std::cout << "printing B" << std::endl;
}
};
int main() {
A* a = new A();
a->printSometext();
return 0;
}
How C++ o... | Well, that's an interesting question, but let me try to answer that in a very methodical manner !!!
let's say compiler has to resolve a call like this : *
a->someFunc();
*.
Now, compiler will go over following steps methodically.
1.) Firstly, compiler knows the declared type of variable a, so it will check whether ... |
5,374,862 | 5,375,060 | Can I get file attributes (hidden/archive...) with boost filesystem? | I am using boost::filesystem to copy a directory recursively. I would like to exclude hidden files. Is it possible to get the FAT32 file attributes like "hidden" or "archive" using boost filesystem?
Thanks,
Philipp
| Boost::filesystem currently restricts itself to POSIX file attributes. However, the file_status class documentation indicates that the implementation could be extended at any time. I would guess this is just waiting on someone motivated to do the work.
|
5,374,955 | 22,225,082 | How to call OpenTokenByLogonId function? | I am REALLY trying to find a way to call OpenTokenByLogonId() function, and I am pretty stuck. Moreover I can't find any examples of it anywhere!
From MSDN a pointer to OpenTokenByLoginID() can be found in LSA_SECPKG_FUNCTION_TABLE function table received from the SpInitialize() function.
a pointer to SpInitialize() fu... | As Luke said, this function is not being called, but when one implements SSP/AP for the LSA, one can implement this function.
|
5,374,979 | 5,375,039 | Will null iterators cause undefined behaviour? | using namespace std;
class myList
{
public:
mylist():_internalList(),_lastPostition(0)
{
}
typedef list<string>::iterator Itr;
bool enqueue(string);
Itr next()
{
if(_lastPostition == 0)
_lastPostition = _internalList.begin();
if(_lastPostition == _internalList.end())
... | "Is it safe to assign 0 to an iterator and check for 0 ?" No.
|
5,375,024 | 5,375,049 | How can I concisely compare a single variable to many different values? | I know you can write a statement like:
if (num1 != a && num1 != b && num1 != c ..........&& num1 != z)
(do something);
But is there an easier way to compare the num1 variable to 26 other variables? Kinda like:
if (num1 != a,b,c,d,e,f,g.......)
(do something);
| If a..g are contiguous constant/enum values then just use a range check.
if (num >= a && num <= g)
{
do_something();
}
else
{
do_something_else();
}
If they are non-contiguous but constant then maybe use a switch statement.
switch (num)
{
case a:
case b:
case c:
case d:
case e:
case f:
... |
5,375,126 | 5,375,800 | Ruby C++ style iterator | I would like to iterate through different ruby arrays (and possibly hashes). I don't really want to have to maintain an index to keep track the position I am in for each array. It's not because I'm lazy, but I am used to the C++ way of using iterator, which I think is less error prone.
So is there a way to get an itera... | The Enumerable methods only iterate if you provide a block, otherwise they return an iterator that is similar to the C++ ones. For example, in irb:
>> e = [1,2,3,4].each
=> #<Enumerator: [1, 2, 3, 4]:each>
>> e.next
=> 1
The tricky thing is that .next is pretty much like e++ in C++ as it returns the current value and ... |
5,375,356 | 5,375,512 | Does the imlementation of std::string, I use, implement ref-counting or not? | I develop for iOS and use XCode 3.2.5, GCC 4.2.
UPD
This code works:
string s = "aaaa";
string s1 = s;
assert(s.data() == s1.data());
Does it mean ref-counting is used? Or '==' is overloaded for const char* somehow to compare contents, not addresses?
UPD
Okay, it does.
| There are different ways of finding out, the first of which is plainly looking at the code. std::string is a typedef to an instantiation of the basic_string template, and being a template, all the code is available to you in the headers. Note that reading standard library headers can be both enlightening and hard. And ... |
5,375,398 | 5,376,825 | Syntax Error in Preprocessor Macro Code | I am trying to write some code for a macro which returns the length of a string, and am attempting to implement it using BOOST_PP_WHILE. The code stems from the fact that a character at a position specified by position of the string represented by a macro argument foo may be obtained by #foo[position]. Compiling using ... | How about this - http://codepad.org/aT7SK1Lu
Its still a compile-time strlen, and would be likely much faster to compile.
#include <stdio.h>
#include <string.h>
#define TEST_STRING "Hello, World!"
template <int N> struct xtmp2 { typedef char (&t)[N]; };
template< class T, int N > typename xtmp2<N>::t xlen( T (&)[N] )... |
5,375,597 | 5,375,985 | Template array initialization with a list of values | In standard c++ we can write :
int myArray[5] = {12, 54, 95, 1, 56};
I would like to write the same thing with a template :
Array<int, 5> myArray = {12, 54, 95, 1, 56};
assuming that
template <class Type, unsigned long N>
class Array
{
public:
//! Default constructor
Array();
//! Destructor
virtua... | My solution is to write a class template that accumulates all the values which get passed to the constructor. Here is how you can initizalize your Array now:
Array<int, 10> array = (adder<int>(1),2,3,4,5,6,7,8,9,10);
The implementation of adder is shown below with complete demonstration:
template<typename T>
struct ad... |
5,375,711 | 5,375,737 | File handling compilation error | I have a problem with file handling. I'm writing code for file handling, that looks like this:
ofstream SaveFile("/home/core-site2.xml")
//SaveFile<<"<?xml version="1.0"?>" ;
SaveFile <<endl ;
SaveFile<<"<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>" ;
When I compile this file I get the following erro... | The declaration of SaveFile misses a trailing ';'. Also, you need to escape the quotes inside the string:
SaveFile<<"<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>" ;
|
5,375,714 | 5,376,184 | Verifying CRT used in library (.lib) | How do I check what runtime library a static library (.lib) in Windows has linked to?
I'm compiling my project with /MDd and I presume a library I'm linking to is using /MTd Multi-threaded Debug
Error 7 error LNK2005: "public: __thiscall std::_Lockit::~_Lockit(void)" (??1_Lockit@std@@QAE@XZ) already defined in libc... | I was able to fix this doing the following
> dumpbin /DIRECTIVES C:\..\ThirdParty\tidy\windows\lib\libtidy
.lib
Microsoft (R) COFF/PE Dumper Version 10.00.40219.01
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file C:\..\ThirdParty\tidy\windows\lib\libtidy.lib
File Type: LIBRARY
Linker Direc... |
5,375,978 | 5,376,170 | How to signal a thread in linux? | I am working on multi-threaded application where I am using SetEvent() to close the thread on windows.
What is the equivalent in linux c++ to send a signal to a thread? The application has to run on both windows and linux.
In windows, I am doing the following:
In the UI I have a button say Close thread. Once the user ... | If you are writing a cross-platform GUI application, you probably already use some cross-platform GUI framework, like Qt or WxWidgets. These frameworks usually come with their own cross-platform libraries for all sorts of things, including multi-threading. So instead of using native APIs, check out the documentation of... |
5,376,045 | 5,376,195 | c++ file handling problem | hi everybody out there i need help from u in file handling
I'm using Ubuntu as my operating system
now my c++ code has a line remove("/home/manish.yadav/Desktop/ram.txt");
last time i ran this command in C code it remove my operating system
now I'm not sure to use it or not ?
can anyone tell me proper syntax of this... | Take a look into the reference page for std::remove on how to use it to remove files.
Concerning your OS, std::remove doesn't randomly kill OSs. Last time I tried it, the function worked as expected.
|
5,376,577 | 5,376,638 | Incremental field in visual studio project properties | What does the field incremental linking mean in the property pages of a project in visual studio?
What should it have in release and what in debug?
I found in the project that i am workin on that it is incremental in debug and incremental:no in release, does anybody know why?
| Incremental linking allows the linker to modify the existing linked dll/exe instead of recreating it from scratch whenever something's changed and you build. Enabling it allows edit-and-continue to work - but in my experience it's not 100% reliable, so I'd recommend that you avoid it at least in release.
|
5,377,069 | 5,415,689 | Com error 800a03ec when i call PrintPreview() method of workbook | Show message of Com error 800a03ec when i can PrintPreview() of workbook
m_spWorkbook->PrintPreview();
i get m_spWorkbook in the following code:
hr = spOleObject->QueryInterface(__uuidof(_Workbook), (void**)&m_spWorkbook);
what's the problem?
| Exception 800a03ec often means problem with locale. For example, language in Excel differs from regional settings. Have a look at these links:
http://blogs.msdn.com/b/eric_carter/archive/2005/06/15/429515.aspx
http://support.microsoft.com/kb/320369
As I understood from your other question, HRESULT 0x800a03ec throwin... |
5,377,411 | 5,377,465 | Non-const declaration of array | I have been teaching myself programming for couple of years, and I was sure that if you need array declaration of a variable number you need to use malloc or new.
Today I found that this compiles under g++ version 4.4.4, without warnings or errors:
#include <iostream>
using namespace std;
int main()
{
int size_arr... | This is a C99 feature - VLA - which is not a part of standard c++. You can use it if your compiler supports it and you don't require portability. If the compiler supports it, it's perfectly safe to use - but it's a bad habit using non-standard features.
|
5,377,434 | 5,377,493 | Does std::map::iterator return a copy of value or a value itself? | I'm trying to create a map inside a map:
typedef map<float,mytype> inner_map;
typedef map<float,inner_map> outer_map;
Will I be able to put something inside inner map, or does iterator::second returns a copy?
stl_pair.h suggests the latter:
74: _T2 second; ///< @c second is a copy of the second object
but my... | The comment in stl_pair.h is misleading in this specific case.
There will be no copy, since the map::iterator actually refers to the original data inside the map (the value_type, which itself is a pair), it’s not a copy. Thus iterator::second also refers to the original data.
|
5,377,496 | 5,377,583 | Position-independent code and vtable | How are virtual functions implemented in position-independent code?
I know that if my class has virtual functions, the compiler usually generates a vtable for it that contains addresses of all virtual functions, and stores a pointer to the vtable in each object of my class.
Now, if my code is position-independent, the ... | There are two options:
accept that your vtable is not going to be position independent, and try to move it away from the code section, so that all code that needs dynamic linking fixups lives next to each other in order to reduce the number of unshareable pages. gcc does this.
use relative jumps in the vtable. I'm not... |
5,377,642 | 5,377,662 | Detect whether path is absolute or relative | Using C++, I need to detect whether given path (file name) is absolute or relative. I can use Windows API, but don't want to use third-party libraries like Boost, since I need this solution in small Windows application without expernal dependencies.
| The Windows API has PathIsRelative. It is defined as:
BOOL PathIsRelative(
_In_ LPCTSTR lpszPath
);
|
5,377,803 | 5,391,400 | Embedding C/C++ code with syntaxhighlighting into HTML with javascript | Hopefully somebody can point me to something that could help. What I'm doing is designing a few things in a HTML document, but I'd really like to be able to have blocks of C/C++ (not too worried, although I imagine C would be easier) code in the design document. The problem I have is formatting the code - as I'd ideall... | Time to close. Here's a few javascript syntax highlighters:
SyntaxHighlighter
A collection of 9 scripts
|
5,377,988 | 6,058,616 | free to use JBIG2 encoding library for c++ | I´m searching for a JBIG2 encoding library, which is free to use and runs on Windows.
I found this library, but it is not compilable on Windows. It uses some Linux libraries.
It´s really confusing, too.
Does anyone know an alternative to it?
Thanks for your help!
| I found a windows binary of my mentioned library here:
http://soft.rubypdf.com/software/windows-version-jbig2-encoder-jbig2-exe
|
5,377,998 | 5,378,067 | c++ string to ipAddress windows/unix system | can i convert string to ip address in c + + on multiple platforms
Windows (various versions) and Unix systems?
| You can use the inet_addr() function to convert an IP address represented as a string into the form that can be used with other socket functions.
Here's an example use (taken from here):
int rc;
int s;
struct sockaddr_in myname;
/* clear the structure to be sure that the sin_zero field is clear */
memset(&myname, 0, s... |
5,378,071 | 27,463,056 | Format C/C++ code on save | The formatting options of Eclipse avoids me lots of conflicts with other users, and ensure that my code always looks "clean" (especially regarding my git commits).
I know about the "Format on save" option in Java editor, but I could not find one in C/C++.
Is this deliberate?
May I expect to see such option one day? O... | Format on save in CDT is now implemented in Eclipse Mars.
|
5,378,185 | 5,378,564 | Visual Styles within Dialog Based MFC Applications? | The MFC Application Wizard disables visual styles for dialog based applications.
But why?
Regardless of the wizard, can I still use the visual styles in my dialog based application (it includes toolbar and menubar)?
Thank you!
| I think there's a little confusion here.
The greyed out drop-down is title "Visual Styles and colors" in my English version of VS2008. Being greyed out means that you can't modify its value, but it still reports that the resulting app will use "Windows Native/Default". When you go on and create the app and run it, the... |
5,378,273 | 5,378,300 | Largest sum contiguous subarray (Interview Question) |
Possible Duplicate:
Find the maximum interval sum in a list of real numbers.
I was asked the following question today at Adobe interview for the position of software engineer.
Problem Given a array arr[1..n] of integers. Write an algorithm to find the sum of contiguous subarray within the array which has the larges... | You can use Kadane's algorithm which runs in O(n).
Here is the algorithm (shamelessly copied from here)
Initialize:
max_so_far = 0
max_ending_here = 0
Loop for each element of the array
(a) max_ending_here = max_ending_here + a[i]
(b) if(max_ending_here < 0)
max_ending_here = 0
(c) if(max_so_... |
5,378,500 | 5,378,562 | Problem with count() and find() in std::multimap | I want to use std::multimap whose Keys and Values are of type GUID. For that, I needed to define comparison operator. Here is the related question.
struct GUIDPairsComparer
{
bool operator()(const GUID &left, const GUID &right) const
{
if (left.Data1 < right.Data1)
return true;
if (lef... | Your comparison operator is wrong - it doesn't satisfy strict weak ordering.
if (left.Data1 < right.Data1)
return true;
else if (left.Data1 > right.Data1)
return false;
if (left.Data2 < right.Data2)
return true;
else if (left.Data2 > right.Data2)
return false;
if (left.Data3 < right.Data3)
ret... |
5,378,514 | 5,378,529 | Execute external command and wait for it to finish under Linux | Easy question: what is the easiest way to execute an external program (with parameters) from C++ (using g++ and Linux)? Is there an easier way rather than doing fork/exec and waiting? I just need to execute the command and wait for it to finish.
| Kind of depends on how much you want to interact with the program.
If not at all, you can easily just use system("....");
If you want some I/O then you can use popen();
And if even that is not enough, you will end up will fork(), exec(), wait(), dup() and other functions from this family.
|
5,378,677 | 5,378,736 | What does a single "throw;" statement do? | These days, I have been reading a lot the C++ F.A.Q and especially this page.
Reading through the section I discovered a "technique" that the author calls "exception dispatcher" that allows someone to group all his exception handling in one handy function:
void handleException()
{
try {
throw; // ?!
}
catch (... | If you do a throw; on its own, and there isn't a current exception for it to rethrow, then the program ends abruptly. (More specifically, terminate() is called.)
Note that throw; is the only safe way to re-throw the current exception - it's not equivalent to
catch (exception const & e) { throw e; }
|
5,378,906 | 5,379,641 | Qt / C++ - how to store configuration data | What is the best way to store application configuration in a Qt application?
| If You store only list of name-value pairs QSettings class will suffice. It is cross platform and works well.
Check this page for more info:
http://doc.qt.io/archives/qt-4.7/qsettings.html
On the other hand if You have to store data in multiple tables (many params, many rows) I suggest You use Sqlite and QtSQL. Sqlite ... |
5,379,102 | 5,379,184 | Best way to encapsulate "optional" fields within a struct generically in C++? | I have many concrete-structs and I want to designate fields as optional (present or not-present). Just wondering what ideas people have for achieving this. Here is an example struct (fields can be other structs as well, even vectors of structs):
struct LogonMessage_t
{
Header_t header; // this poin... | Sounds like you want boost.optional.
|
5,379,272 | 5,379,387 | C++ template dll => unresolved externals | I have a template function in a shared library. I know the function will be called with either int or double arguments. I therefore instantiate the two versions of the template in the source file.
template void library::doSomething<int>(int const number);
template void library::doSomething<double>(double const number);... | You need to put the mangled names of the instantiated functions into the DEF file, not the C++ names.
You can find out more in the MSDN article Exporting from a DLL Using DEF Files:
If you are exporting functions in a C++ file, you have to either place the decorated names in the .def file or define your exported funct... |
5,379,282 | 5,379,317 | Getting the current process creation time in Linux | How do I get the current process creation time using c/c++ on Linux?
When I'm opening the file /proc//stat
The output is just a bunch of numbers. How do I know which one of them is the creation time?
| The manpage lists the order and meaning of the values of /proc/[pid]/stat. This answer more information.
|
5,379,331 | 5,380,801 | Audio Manipulation In C++ | I hope this is the right place to post this and somebody can help.
I am a music technology student and I've recently picked up learning C++ as it would greatly help my career knowing a programming language, especially this one since it is used in the video games industry.
Anyways onto the main topic. What I want to cre... | If you know the RIFF file structure, you might also already know how PCM audio is stored in it.
A common format is 16-bit stereo pcm. In that case each sample is 2 bytes, and two samples belong together (left+right). But you need to check the format chunk for the exact format. But I asume for now you are manipulating a... |
5,379,333 | 5,379,505 | change variable to reference even if it was not declared as reference | In C++ I can make myReference be a reference of myValue by using & in the declaration of myReference:
int myValue = 123;
int& myReference = myValue;
But if I declare a variable without &, can I later still make it hold the reference to the value of another variable rather than a copy of that value? In other words: Is ... | You can't do this in C++ (a reference must be declared as a reference, and immediately bound to a variable).
If you give us more context on what you are really trying to do here we can offer specific suggestions.
|
5,379,357 | 5,379,461 | Validity of iterator pointing to erased item | On that page, it's said that:
this invalidates all iterator and
references to elements after position
or first.
Does that means position and first iterators are valid after the erase?
(Obviously, I ask that because I want to delete some item in a vector during a for_each loop.)
Thank you.
| According to http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#414 positon and first should be considered invalid - the wording in the standard is unclear but as iterators and references are mentioned in one sentence, and a reference to an erased element doesn't make sense, it was "taken for granted" that er... |
5,379,629 | 5,379,648 | Does unreachable code within #ifdef and #endif get removed during compile/link time? | Does unreachable code within #ifdef and #endif get removed during compile/link time or kept in the executable even though it can not be reached?
#ifdef DEBUG
// some debug operations
#endif
Is the debug operation code still kept after compilation without DEBUG flag, and if it is will it affect the performance of relea... | The preprocessor will completely remove such code - the compiler doesn't even get to see it.
You can e.g. use g++ -E to have a look at what the preprocessor does, and what the compiler gets to see.
|
5,379,643 | 5,379,750 | instantiation in c++ | First of all, I would like to notify you, I have definetly searched for answers about my following question, but im a complete newbie to C++.
I am coming from the luxurious life of C# and Java, now trying to pick up a thing or two about c++
The question is about instantiation.
I use code::block as my IDE of choice.
Cur... | As larsmans said, Person person and Person *person = new Person() are result in the new Person instance being allocated in the stack/heap respectively.
What this means for you (and this is the answer to the "which should I use?" question) is that in the first case, the memory for the object is managed automatically (th... |
5,379,816 | 5,379,868 | problem reconstructing a string removing punctuation | I am trying to write a program to strip the punctuation from a string. The input to the program should be a string of characters including punctuation; the output should be a string in which the punctuation is removed. I am using Visual Studio 2008 to compile and run the program. While executing it I am getting excepti... | You did not set a meaningful size to the output variable, so you are accessing elements that do not exist. You need to output.push_back(input[ix]);
|
5,379,829 | 5,379,856 | Can I use tempnam with IOS? | I'm porting a C++ lib to iOS, and have run into an issue where the code calls tmpnam. The function returns "var/tmp/tmp.0.0xGlzv" which I assume is outside of the "sandbox" that my app is allowed to play in. A subsquent fopen returns "Operation not permitted". Is there a viable replacement?
| What about
[NSTemporaryDirectory() stringByAppendingPathComponent:@"myTempFile1.tmp"];
?
For a unique filename, try something like this:
NSString *uniqueTempFile()
{
int i = 1;
while (YES)
{
NSString *currentPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@... |
5,380,018 | 6,808,899 | Deny Access to Kiosk program process | I have a kiosk app and have to disable task manager always to prevent closing the program by users .
But some users need the TaskManager to close hanging programs.
Any help would be appropriated.
However, I am sure there is a function in windows to prevent closing a program's process , as when one attempt to kill... | One approach, if you could access the process ID in an administrative context, is to deny the PROCESS_TERMINATE permission on the process to end users. Terminating the process (through task manager or other contexts) is by default granted to the owner, but can be explicitly denied. When it is denied, terminating the ... |
5,380,065 | 5,384,366 | MFC static library and external rc(resource) file icon loading problem | I have a problem with loading icons from external resource files in main application. I'll try to explain how application is set right now. The resources of the main application includes external dialog *.rc and appropriate *.h. And linker includes dialog implementation (CDialog/CFormView) which resides in external sta... | Your .rc file is compiled by rc.exe to embed the icon in your executable. rc.exe uses the include path to find the resources. This is specified by either the INCLUDE environment variable or by using /I option to rc.exe. If "my_icon.ico" doesn't work, try moving the file or change the include path.
Clarification:
rc.exe... |
5,380,265 | 5,667,434 | Microsoft SDK Version | The error I am getting is here:
#if defined( _WIN32 )
#ifndef WIN32
#error error // error calls here
#endif
I wrote a program in MS VS2008 that works fine, however when I transfer it over and compile it in MS VS2010, I get a bunch of errors.
Some header files and libraries I include are as follows:
#in... | I figured this out finally. In properties->C/C++->Preprocessor->Preprocessor Definitions add WIN32
|
5,380,294 | 5,380,329 | Blindly converting a bytearray to a structure? | Is it possible to, say, convert a byte array passed from an older C++ application to C# without exactly knowing what the structure is?
I'm trying to re-make an old application that our company uses, but the source code is no longer available. Any help would be greatly appreciated. Thanks!
| You would need to know something about the structure of the byte array if you want to actually use the data embedded in the array. Without that information, the array is nothing but bytes - you could easily pull it in as bytes, but that will be of little use.
If this information is unavailable, you could use a hex edi... |
5,380,326 | 5,380,336 | C++: I have a string representing 8 bits. How Do I convert it to a char? | ie. "11111111" should convert to 0b11111111 / 255 (in dec)
| Try strtol with a base of 2.
|
5,380,358 | 5,380,507 | Which user-defined-literals are predefined by the standard? | My question sounds like a contradiction, but I don't know how else to refer to the new literal syntax other than user-defined-literal.
std::string operator "" s ( const char* str, size_t len )
{
return std::string( str, len );
}
assert( "foo"s == "bar"s );
I remember hearing that user defined literals should start... | The language already use regular literals suffixes, for example 1U.
It would become ambiguous if you were to use U as a user-defined-literal, thus the recommendation.
integer-suffix: u, U, l, L, ll, LL
floating-suffix: f, F, l, L
|
5,380,378 | 5,382,848 | Algorithm for how many students in a class did better than a student given this information | I want to make a simple application that will take in:
number of students
class average (score/100)
median grade (score/100)
class standard deviation
the current grade of a student (score/100)
The output would be how many students did better than that student.
I'm interested in the best estimate possible with this in... | The commenters above are correct that without more information you can't nail this down precisely. However, as Steve Jobs likes to say, real artists ship so here is what I would do if you need a ball park estimate.
The two most straight forward ways to go about this is to either assume the data is normally distributed ... |
5,380,642 | 5,380,712 | Overloading operator= as Non-Member | According to replies to this thread, operator= cannot be overloaded as a non-member function. So, for example, the following makes the compiler very angry:
class MyClass
{
// ...
};
MyClass& operator=(MyClass& Left, MyClass& Right)
{
// ...
}
Why is this? I have a container class with getters and setters, s... | If your class doesn't have an assignment operator (as a member), the compiler generates one by default, just like it generates a copy constructor if you don't provide one.
Therefore it will be "angry" if you try to define a non-member assignment operator later. There will then be two!
|
5,380,857 | 5,380,935 | Erasing the last element of a vector by looping through it | I want to loop through a vector and erase certain elements that correspond to a certain criteria, for example:
vector<int> myvector;
vector<int>::iterator it;
myvector.push_back(1);
myvector.push_back(2);
myvector.push_back(3);
myvector.push_back(4);
for(it = myvector.begin(); it != myvector.end(); ++it){
if((*i... | Don't do this with a for loop, there's already a well-debugged algorithm for you.
myvector.erase(std::remove(myvector.begin(), myvector.end(), 4), myvector.end());
|
5,381,117 | 5,381,697 | std::map lower_bound is not returning the correct value | Good afternoon, I am trying to use the std::map lower_found member function. However , it keeps returning the wrong answer. Here is an excerpt of my test code. Please explain to me how to make std::map lower bound function properly. Thank you.
class Interval {
public:
explicit Interval(int item){
... | IIUC, you're dealing with ranges, and you have an invariant on
the map that ranges don't overlap. If that's the case, you have
to define your operator< so that it deals with ranges, and does
something drastic (assertion failure or an exception) in the
case of an overlap, to prevent such ranges from being inserted.
Ass... |
5,381,309 | 5,381,424 | how to make a copy of boost::filesystem::directory_iterator? | I know this sounds stupid, but look at this simple example (working dir should have more than one item):
#define BOOST_FILESYSTEM_VERSION 3
#include <boost/filesystem.hpp>
#include <cassert>
int main()
{
using namespace boost::filesystem;
directory_iterator it("./");
directory_iterator it_copy = it;
++... | If you take a look at the reference you will notice that it is advertised to be a boost::single_pass_traversal_tag.
This is the equivalent (in boost terminology) of the Input Iterator in the STL (think of it as an iterator delivering packets from a network connection, you cannot rewind).
Also note (from this same page)... |
5,381,364 | 5,381,454 | C++ Thread Safety Summary | I would like a summary of what exactly is thread safe in C++ both according to the current standard and C++0x as well as in practice (generally speaking, but also in my case with gcc 4.5.1).
For STL containers, my understanding is that thread safety is not guaranteed according to the current standard. Is it true thoug... | The current standard doesn't mention threading at all, in any respect. In practice, the standard containers provide thread-safe reading, but require synchronization for writing.
C++ 0x doesn't talk much (at all?) specifically about containers with respect to thread safety/sharing, but does talk about assignments and su... |
5,381,909 | 5,382,051 | Bison: Shift Reduce Conflict | I believe I am having trouble understanding how shift reduce conflicts work. I understand that bison can look ahead by one, so I don't understand why I am having the issue.
In my language a List is defined as a set of numbers or lists between [ ].
For example [] [1] [1 2] [1 [2] 3] are all valid lists.
Here are the de... | I think I'd define things differently, in a way that avoids the problem to start with, something like:
value: num
| stringvalue
| list
;
items:
| items value
;
list: LEFTBRACE items RIGHTBRACE;
Edit: Separating lists of numbers from lists of strings can't be done cleanly unless you eliminate... |
5,381,937 | 5,381,972 | Is the constructor getting called here? | #include<iostream>
class _ctor
{
public:
_ctor() { std::cout<<"\nCtor";}
~_ctor(){ std::cout<<"\nDtor";}
};
_ctor A(); // --> Is the Constructor Really called? I do not see the Output printed
//_ctor A;
int main(){
return 0;
}
The Output of the above code is given in this Link
I don't see the constructor getting ca... | You declared a function called A() which returns a _ctor, and you never called that function. You never even defined that function.
No, the constructor of _ctor is not being called.
|
5,382,037 | 5,382,090 | Non-repeating random number generator | I'd like to make a number generator that does not repeat the number it has given out
already (C++).
All I know is:
int randomgenerator(){
int random;
srand(time(0));
random = rand()%11;
return(random);
} // Added this on edition
That function gives me redundant numbers.
I'm trying to create a questionnaire pr... | What I would do:
Generate a vector of length N and fill it with values 1,2,...N.
Use std::random_shuffle.
If you have say 30 elements and only want 10, use the first 10 out the vector.
EDIT: I have no idea how the questions are being stored, so.. :)
I am assuming the questions are being stored in a vector or somesuch... |
5,382,242 | 5,382,369 | How am I getting a linker error: Unresolved external symbol | This is in a Windows Console application, so I have no idea how this is happening at all.
#include "Library.h"
//poglathon.cpp
//starting region
bool Poglathon(std::vector<std::string>& text,Player *player){
using namespace std;
cout << "You see a town to one side and a path leading to a dark, murky forest i... | Your declaration in the header file looks like this:
bool Poglathon(std::vector<std::string>& text,Player player);
Your attempt to define in the cpp file looks like this:
bool Poglathon(std::vector<std::string>& text,Player * player);
Change the declaration to take a Player * instead of a Player
|
5,382,404 | 5,384,449 | Difference between pragma once inside and outside include guards? | Is there any difference between placing the #pragma once inside the include guards as opposed to outside?
case 1:
#ifndef SOME_HEADER_H
#define SOME_HEADER_H
#pragma once
case 2:
#pragma once
#ifndef SOME_HEADER_H
#define SOME_HEADER_H
I'm just wondering out of curiosity if there's any special cases where I should pr... | There's a subtle difference in that if SOME_HEADER_H is already defined before the header is included, then in the second case the preprocessor will process the #pragma once, and in the first case it won't.
You'll see a functional difference if you #undef SOME_HEADER_H and include the file again by the same TU:
#define... |
5,382,415 | 5,382,462 | C++ template refinement involving another typename? | Without using Boost, how can I write a function like:
template<typename T>
void myFunc(T t)
{
...
}
template<>
void myFunc(someclass<T> t)
{
myFunc(t.get());
}
Update: I may have over analyzed this. I was confused when I wanted the original
template<typename T>
void myFunc(T t)
{
...
}
to work with vecto... | Not sure why you associate Boost with this. Anyway:
This won't work since T doesn't exist here.
template<>
void myFunc(someclass<T> t);
What you probably meant is:
template < typename T >
void myFunc(someclass<T> t);
|
5,382,451 | 5,382,504 | How to use std::ifstream to read in a binary file with a wide string path | I am reading a binary file as:
const size_t stBuffer = 256;
char buffer[stBuffer];
std::wstring wPath(L"blah");
std::wifstream ifs(wPath.c_str(), std::wifstream::in | std::wifstream::binary)
while (ifs.good())
{
ifs.read(buffer, sizeof(buffer));
...
}
But I am realizing this is not a true binary read. The ifstream... | The current C++ standard doesn't provide wide char paths. Even the wchar_t version receives a regular const char* filename. You already used a compiler extension, so continue using this extension with a normal ifstream:
std::wstring wPath(L"blah");
std::ifstream ifs(wPath.c_str(), std::ios::in | std::ios::binary)
EDIT... |
5,382,468 | 5,382,549 | "__comp cannot be used as a function" c++ while trying next_permutation | I'm trying to do permutations with next_permutation from the stl, however I'm getting an error and I can't figure out how to fix it. I've tried googling, however the only results that come up are when people used the same function and function's variables name but thats not the case here.
Here's the error :
'__comp' ... | H = rec4.w + max(rec1.h, rec2.h, rec3.h);
You don't want to pass rec3.h there - The error message simply say that the 3rd argument to max can't be used as a function. I believe you intended:
H = rec4.w + max(max(rec1.h, rec2.h), rec3.h);
|
5,382,883 | 5,382,896 | C++ for loop and switch statement logic error | In this loop (assuming amount is 2), instead of printing:
1. [op1]
2. [op2]
it prints:
1. [op1]
2. [op2]
3. [op3]
4. [op4]
5. [op5]
Why? How can I fix this?
for(int i=1;i<=amount;i++){
//string s;
switch(i){
case 1:
cout << i << ". " << op1 << endl;
... | You need to use break; or switch() will have what's called "fallthrough".
(This means that it executes your case: and then continues on anything that comes afterwards, including code in other case statements).
|
5,382,940 | 5,383,000 | Broken pipe when socket is closed | I have a server/client app on a Linux box. If the server is not up when the client attempts to send a request, I get a SIGPIPE and the application terminates.
How can I check if the server is available on the socket before I try to write?
Also of note, I do not want to trap the SIGPIPE because the client is really part... | Pass MSG_NOSIGNAL as flags to send()
|
5,382,951 | 5,383,607 | How do I detect row selections in QListView <- > QAbstractListModel with Item Delegate? | It seems there is zero built-in selection support with my choice of QListView -> QAbstractListModel. Do I have to write everything from scratch? the catching of a selection event in the UI, the marking of the model item as selected, etc? It seems there is no out-of-the-box support for this.
the weird thing is that ther... | QListView is derived from QAbstractItemView, which has a method to get the selection model:
QItemSelectionModel *selectionModel = myView->selectionModel();
This method returns a pointer to the selection model, which is long-lived, i.e., you can save the pointer, connect to its signals, etc.
|
5,383,109 | 5,383,192 | Setting a Forms ClientSize changes the Location of the control | I am resetting the size of a Form in a Control derived from Panel in the OnLayout handler after changing the control's size.
panel->ClientSize = size;
this->Parent->ClientSize =
System::Drawing::Size(
this->Parent->ClientSize.Width,
this->Parent->ClientSize.Height-difference);
Stepping through th... | I would check to see how the control is anchored to it's parent.
|
5,383,293 | 5,383,442 | Linker error when using boost threads | I'm trying to use the boost threads, but when running the program i get this:
LINK : fatal error LNK1104: cannot open file 'libboost_date_time-vc100-mt-gd-1_46.lib'
The directories I've included in the linker, are: c:\boost_1_46_0\libs\ and c:\boost_1_46_0\boost.
And I am using Visual Studio Express 2010.
Thanks.
| Specify $(BOOSTROOT)/lib as 'additional library directory' for the linker. ( Note: it is NOT libs with an s )
This assumes that you have built the boost libraries using the visual studio compiler. From the discussion in the comments, it seems you have not done this.
I recomend, instead of trying to build the librarie... |
5,383,296 | 40,027,292 | What happens to the thread affinity of a QObject created within a worker thread which then terminates? | Let's say I call QtConcurrent::run() which runs a function in a worker thread, and in that function I dynamically allocate several QObjects (for later use). Since they were created in the worker thread, their thread affinity should be that of the worker thread. However, once the worker thread terminates, the QObject th... | QThread is not documented to automatically move any QObjects when it finishes, so I think we can already conclude that it does no such thing. Such behavior would be very surprising, and at odds with the rest of the API.
Just for completeness, I tested with Qt 5.6:
QObject o;
{
QThread t;
o.moveToThread(&t);
... |
5,383,429 | 5,383,969 | What algorithm is behind STL's find? | I just created a custom finding function for strings in a map. I developed some kind of the linear search algorithm (which I found out later) and was not satisfied with the speed of the function. So I searched for a faster function and found map's own function: map::find.
This was incredibly faster than the linear algo... |
I developed some kind of the linear search algorithm (which I found out later) and was not satisfied with the speed of the function. So I searched for a faster function and found map's own function: map::find.
This was incredibly faster than the linear algorithm I was using.
std::map is designed to keep data sorted a... |
5,383,642 | 5,383,710 | To invoke a variadic function with unamed arguments of another variadic function | I have two variadic function as foo(format, ...) and bar(format, ...). I want to implement function foo so that it can invoke bar with the same list of arguments it has. That is,
foo(format...)
{
...
bar(format, ...);
}
For instance, invoking foo("(ii)", 1, 2) will invoke bar with same arguments bar("(ii)", 1, 2). ... | Can't be done, as long as all you have is a bunch if functions with ... arguments.
You have to plan ahead for things like that and implement each variadic fuinction in two-staged fashion
void vfoo(format, va_list *args) {
/* Process `*args` */
}
void foo(format, ...) {
va_list args;
va_start(args, format);
vfo... |
5,383,807 | 5,383,836 | Using `cout` to View Binary Data on Console | I'm writing a test application, and I'd like to keep it as simple as possible. I recall that there is a way to use cout to print binary data to the console in ASCII format. For example:
int myVar = 0x1234;
cout << "My variable: 0x" << myVar << endl;
Hopefully, this would print to the console something like this:
My... | You seem to want to print the binary data in hexadecimal format. This can be done using the hex manipulator:
#include <iostream>
using namespace std;
// ...
int myVar = 0x1234;
cout << "0x" << hex << myVar; // 0x1234
Note that this only works for integers.
|
5,384,358 | 5,384,593 | How does a sentinel node offer benefits over NULL? | On the Sentinel Node wikipedia page it says that the benefits of a sentinel node over NULL are :
Increased speed of operations
Reduced algorithmic code size
Increased data structure robustness (arguably).
I don't really understand how the checks against a sentinel node would be faster (or how to properly implement th... | There's no advantage with sentinels if you're just doing simple iteration and not looking at the data in the elements.
However, there's some real gain when using it for "find" type algorithms. For example, imagine a linked list list std::list where you want to find a specific value x.
What you would do without sentinel... |
5,384,397 | 5,384,917 | What is a QVariant and when should it be used? | What is a QVariant and when should it be used?
| QVariant is used to store references to values where you don't necessarily know what is inside. It's a way to create APIs that can accept "anything" as a reference to an unknown type. IE, instead of having to have an API that accepts a long, and another for an int, and another for a float, and another for a string yo... |
5,384,492 | 5,384,646 | How to unload C++ DLL in C# | I load a C++ DLL using DLLImport in my C# ASP.Net web application. The DLL basically reads some CSV files, and manipulates them and creates new files.
After I ran the method successfully, and run it again then I get C++ exception back.
I want to unload the C++ DLL from the website so a user can re- load the DLL and r... | As far as I'm aware, there's no way to do late binding with C#.
You can do it by creating a C++ DLL and using that, however. Assuming you know enough about C++ to do this, you would just need a single function exported by the DLL, which uses LoadLibrary to load your CSV manipulation DLL, GetProcAddress to retrieve the ... |
5,384,505 | 5,384,529 | what is the best solution/architecture for implementing localization in an application written in unmanaged C? | what is the best solution/architecture for implementing localization in an application written in unmanaged C ?
Should I use MUI, something based on boost::locale or something very classic (I will post this below as first response). Or maybe something else... setlocale seems too simple.
Can I change language at runtim... | The standard approach seems to be: One directory for each language that will contain module localizations (dlls containing text and images). Most probably one for each module in application and will contain only resources.
Application will set this module as default (using AfxSetResourceHandle or something equivalent) ... |
5,384,665 | 5,385,124 | Finding the nearest XY coordinates | I've got a point in 2d image for example the red Dot in the given picture and a set of n points blue dot (x1,y1)...(xn,yn) and I want to find nearest point to (x0,y0) in a way better than trying all points. Like to have best possible solution. Would appreciate if you share any similar class if you have.
| Most solutions that we could suggest would depend on a little bit more knowledge, I am going to go out on a limb and say that unless you already know that you are short on time. I.e. there are tens of thousands of blue dots or you have to do thousands of these calculations in a short time. "Linear Search" will serve yo... |
5,384,753 | 5,385,857 | boost deadline_timer not waiting | I tried using the boost deadline_timer in this simple test application, but had some trouble. The goal is for the timer to trigger every 45 milliseconds using the expires_at() member function of the deadline_timer. (I need an absolute time, so I'm not considering expires_from_now(). I am also not concerned about drift ... | You are mixing local time with system time. The time that asio is comparing your local time to is most likely some number of hours after the time that you want your deadline set to so wait returns immediately (depending on where you live; this same code could wait for several hours as well). To avoid this point of con... |
5,384,871 | 5,384,900 | Exceptions to the order of destruction for temporary objects? | Reading clause 1.9/14 of the C++0x draft. There I find:
Every value computation and side effect associated with a full-expression is sequenced before every value computation and side effect associated with the next full-expression to be evaluated.8)
And the footnote 8 says
8) As specified in 12.2, after a full-expre... | I assume they're referring to any temporaries bound to references. The lifetime of the temporary is extended to the lifetime of the reference, while other temporaries may still be destroyed.
|
5,385,018 | 5,385,228 | Deadlock when closing a pipe fd | I am porting some Unix code to Windows which redirects stderr and stdout to a pipe that I created and there's a thread which reads from this pipe and then sends the output to the debug console. This works fine on Unix, but I can't get it working on Windows. The problem occurs when the read side of the pipe is closed.... | It is possible that the _read implementation on windows returns -1 when _close is called while it is blocked. If it is called after your _close completes, it should return -1 as per the documentation. So, it looks like your thread would get stuck in the main loop, because it only terminates when the return value is zer... |
5,385,148 | 5,385,413 | Get CMake to execute a target in project before building a library | I am using CMake to build my C++ project and it has multiple executables and a library (all part of same project). All is working fine, however one of my executables is a code generator that creates some of the library classes. I have got all the generation working but can't figure out how to call this executable (cod... | In CMakeLists.txt:
First, define your executable:
add_executable(marks-code-generator gen.cpp)
Then, define a custom command to generate the source:
add_custom_command(OUTPUT generated.cpp generated.hpp
COMMAND marks-code-generator ARGS args here maybe
MAIN_DEPENDENCY input-file.i... |
5,385,227 | 5,385,564 | How do I send objdump result to a file? | I want to run objdump on an execuatble file in windows XP, and want to observe the details. However, I am unable to find option to output the result in a text file - since the output display in console is chopped off
(I also tried using the options -o or /out to specify ooutfilename, but do not seem to exist)
| Doesn't the shell's normal output redirection work for you? Example:
objdump -d file.o > file.txt
|
5,385,231 | 5,389,113 | TreeListView control | I need to implement TreeList control same as in Process Explorer.
I am quite newbie in GUI and did not write such complicated controls.
As I see in Process Explorer, there is a TreeListWindowClass, which contains children:
2 headers, 3 scrollbars (one of them is invisible?) and 1 static (place between visible scrollbar... | I did this recently and used the Multi-Column Tree View from http://www.mimec.org/articles/mfc/mctree
It is fairly basic, but it met my needs and is fairly compact. It provides a CColumnTreeView class which is a sub-class of CView - so it works correctly with the standard CDocument/CView pattern of MFC.
|
5,385,355 | 5,385,515 | C++ passing a derived class shared_ptr to a templated function | First something that should work, then something that doesn't. Why doesn't it is the question.
I declare two classes:
class Base { ... };
class Derived : public Base { ... };
I then have the following function elsewhere:
void foo(shared_ptr<Base> base);
The following code should work right?
share_ptr<Derived> deri... | I don't think the compiler will go through a level of indirection in that way. Rather, you can explicitly instantiate foo with TYPE set to Foo. Eg, the following compiles via g++:
#include<boost/shared_ptr.hpp>
class Foo {};
template <typename T> class Base {};
class Derived : public Base<Foo> {};
template<typename T... |
5,385,364 | 5,385,464 | What does exactly the "status" in pthread_join represent and how to query it | I'm wondering what exactly the "status" parameter in the pthread_join is for
int pthread_join(pthread_t thread, void **status);
I'm trying to make use of it but I cannot understand what exactly does it represent.
According to the documentation
status
Is the location where the exit status of the joined thread is stor... | The status is set to the value returned by the function that the thread starts executing (or from the value passed to pthread_exit() if the thread exits early).
Example:
void* thread_func(void* data)
{
if (fail())
{
pthread_exit((void*)new int(2)); // pointer to int(2) returned to status
}
... |
5,385,504 | 5,385,517 | Reference C++ struct object in another file? | I'm in the process of trying to make a game-in-progress more modular. I'd like to be able to declare a single array of all the room_t objects in the game (room_t rooms[]), store it in world.cpp and call it from other files.
The truncated code below does not work, but it's as far as I've gotten. I think I need to use ex... | Just add extern room_t rooms[]; in your world.h file.
|
5,385,629 | 5,505,046 | How can I add custom two-factor authentication with C++, Pam & Ubuntu? | I am looking to add my own 2-factor authentication to my ubuntu linux server with c++. I am going to have my asterisk box call my cell phone with a unique ID, which must be entered at the linux login prompt, before or after a password, with (or) without a certificate - depending on how I configure it. Either way, I'd... | I've written a c++ application to change the password of accounts listed in a MySQL database to be "Pin Number" + OpenSSL Library's RNG to create a 8 letter password - it combines them and forces a password change every 60 seconds.
|
5,385,675 | 5,385,685 | Calling default constructor | I have a problem with a default constructor in C++. It's a simple thing but can't see what's wrong with it.
I have a constructor with 3 optional parameters, with const values on initialization list:
data::data(int D = 1, int M = 1, int Y = 1583) : Day(D), Month(M), Year(Y)
{
if (!CorrectDate()) throw "Wrong Da... | data tomorrow(); is a declaration of a function that returns a data and takes no parameters. To create a data object with no explicit constructor arguments, just do data tomorrow; without the parentheses.
|
5,385,725 | 5,385,737 | How do I define a class that can only be instantiated via new (ie not on the stack)? | I want to arrange things such that for a class Foo, this works:
Foo *f = new Foo()
but this does not (preferably a compile-time error):
Foo f;
Can this be done?
The specific reason is that Foo is actually a tracking class to make another heap-allocated object appear in a script environment. Foo's internals keeps a ma... | Make the constructor private, have a create() which would allocate an instance of the object on the heap and return a pointer. You would have to handle deallocation yourself though.
For eg:
Foo *f = Foo::create();
and later:
Foo::destroy(f);
|
5,385,820 | 5,385,851 | Convert char** to char[x][x] | In C++, I want my class to have a char** field that will be sized with user input. Basically, I want to do something like this -
char** map;
map = new char[10][10];
with the 10's being any integer number. I get an error saying cannot convert char*[10] to char**. Why can it not do this when I could do -
char* astring... | Because an array is not a pointer. Arrays decay into pointers to their first elements, but that happens only at the first level: a 2D array decays into a pointer to a 1D array, but that's it—it does not decay into a pointer to a pointer.
operator new[] allows to allocate a dynamic array of a size only known at runtime... |
5,385,875 | 5,385,883 | Linux ext3 and ext4 files - compatability question | I have developed (compiled) some (C/C++) applications on my local machine, which has the ext4 file system. I want to deploy the compiled binaries to my server - which has a ext3 file system format.
Can I simply create a package and deploy the binary on the server - or are the file systems incompatable?
BTW, both my loc... | You absolutely can. File system formats are completely irrelevant to binary executable formats. You can transfer files from one system to another with no ill effects.
Of course, if your program has external dependencies (shared libraries) then the other system might not have all that's necessary to run your program -- ... |
5,385,981 | 5,393,835 | evaluating multiple integrals | Is there any library to evaluate multidimensional integrals? I have at least 4 (in general much more than that), where the integrand is a combination of variables, so I cannot separate them. Do you know of any library for numerical evaluation? I'm especially looking for either matlab or c++, but I will use anything tha... | Since you don't specify the kind of integrals or the actual dimensionality, I can only suggest that you take into account that
where the function F(x) is defined as
and use this fact to compute your integrals with the usual quadrature techniques. For example, you could use trapz or quad in MATLAB. However, if the ... |
5,386,109 | 5,402,406 | CoreMIDI on the command line | I've started working on a command-line app based on RtMidi that can send arbitrary MIDI data. I've found that, while I can talk to MIDI devices when I run the tool from the console, if I ssh in to my machine from another, I can't get any MIDI functionality to work at all. To be specific, RtMidi makes a call to MIDIClie... | Error code -10839 corresponds to the symbol named kMIDIServerStartErr. I suspect that the CoreMIDI server requires a connection to SystemUIServer (ie, a graphical login).
|
5,386,123 | 5,386,246 | Google V8 JavaScript Engine - How to set a value to null? | Using the V8 engine, how do I set a value to null? Basically I want to return a variable from a C++ addon to JavaScript, and the variable needs to be set to null under certain conditions.
| You can explicitly return null via v8::Null:
return scope.Close( Null() );
Also, it turns out that if a Value variable is declared, it is automatically assigned to undefined. For example, the following returns undefined back to JavaScript:
HandleScope scope;
Local<Value> result;
...
return scope.Close(result);
|
5,386,133 | 5,386,256 | C++ Static Class member refers to self | I'm curious as to whether this is something that I can do:
using namespace tthread;
class E_thread {
static std::list<E_thread*> all_threads;
thread th;
E_messageQueue queue;
public:
E_thread(void (*threadFunction)(void *), void * threadFuncArg) {
all_threads.push_back(this);
th = thread... | This is fine, mostly. You need to protect access (reading or modifying both) to all_threads with a mutex of some sort. Also, you would be better served to use a ::std::set if you destroy threads often during the course of your program.
Also, I sort of question having global variables of any kind. I think it would be cl... |
5,386,186 | 5,386,191 | Class Return Type Overloading | I commonly run into the following situation where I have a data structure which I'd like to have access as follows:
class data {
public:
double error;
double value;
...
}
...
data *outputs;
...
double lastValue = ...;
double someValue = ...;
for (int i = 0; i < n; ++i) {
outputs[i] = someValue; //... | You can add an assignment operator overload to data:
class data {
public:
double error, value;
void operator=(double d) { value = d; }
};
Though, to be honest, I think this would be rather confusing. It depends on how you intend to use it, of course, but given your example, I think it would be cleaner to add... |
5,386,341 | 5,386,362 | What is faster: noop function call or if statement? | I got a function pointer for a deleter, but most of the time, the deleter is not gonna be needed, only when I maintain an internal copy of something. Currently I do that with a noop deleter function:
class MyClass{
public:
// bind object
template<class Type>
void Bind(Type* obj){
Cleanup();
object_ = obj;... | Function call has to setup a stack frame. All the if-statement has to do is execute a single machine instruction. Maybe two, depending on the rchitecture of the machine.
|
5,386,513 | 5,392,224 | Boost::Spirit::Qi Auto-rules and conditional actions | This is probably a pathetically easy question, especially since I've been successfully using QI to parse simple structures for a while now, and probably should already know the answer, but it eludes me regardless...
Let's say we have a container like:
struct GenderTally
{
std::vector<std::string> males;
std::vector<s... | What I'd do in your case is this:
BOOST_FUSION_ADAPT_STRUCT(
GenderTally,
(std::vector<std::string>, males)
(std::vector<std::string>, females)
);
rule<Iterator, std::string()> r = +alnum;
rule<Iterator, GenderTally()> g =
*( ("f:" >> r)[phx::push_back(at_c<0>(_val), _1)]
| ("m:" >> r)[phx::... |
5,386,542 | 5,386,580 | C++: implicit linked list | Why is this not a more popular idiom/pattern?
#include <list>
class A {
int data;
static std::list<A*> glist;
public:
A():data(0) {
glist.push_back(this);
}
~A() {
glist.remove(this);
}
};
It's like a safety net. You can delete an instance of A from any pointer to it and the list manages itself. ... | It's not thread safe. Sometimes you're already maintaining the object list and don't care. Objects on the stack don't really need to be tracked in another container. It introduces a new dependency of your class that may not be needed. I'm sure there are many more reasons I missed.
The object management issues aren't is... |
5,386,827 | 5,387,372 | How to open the file in class in mfc? | While trying to open the file in Class in function oninitdialog(),It throws exception.If I open the file globally , it works.
How to overcome this?
why the fopen command is behaving like these?
Regards,
karthik
| Actually I made a mistake by creating file descriptor in OninitDialog function in mfc.To overcome this , I create the file descriptor in constructor of the class.
|
5,386,834 | 5,386,883 | c++ get base class object from derived class pointer? | Suppose I have Derived* derivedPtr;
I want Base baseObject from the derivedPtr;
Base baseObject = *derivedPtr; would create the baseObject with the appropriate Base class member variables?
Thank you
| It is Object Slicing
Derived* obj = new Derived;
base objOne = (*obj) ; // Object slicing. Coping only the Base class sub-object
// that was constructed by eariler statement.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.