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,115,166 | 5,115,234 | How to construct a std::string from a std::vector<char>? | Short of (the obvious) building a C style string first then using that to create a std::string, is there a quicker/alternative/"better" way to initialize a string from a vector of chars?
| Well, the best way is to use the following constructor:
template<class InputIterator> string (InputIterator begin, InputIterator end);
which would lead to something like:
std::vector<char> v;
std::string str(v.begin(), v.end());
|
5,115,193 | 5,116,666 | C++ - is there any way to get the current executing line | I need to create an exception handling, in that I also asked to print the status of the operation like
"file open : The operation completed successfully"
"file close: The operation completed successfully",
etc.
Is there any macro for this like __LINE__,__FUNCTION__,__FILE__?
Or is there any boost function available to... | I think the answer is that you want to stringify the expression you are evaluating?
Code:
#include <stdexcept>
#include <sstream>
#include <iostream>
void check_result(bool result, const char* file, int line_number, const char* line_contents)
{
if (!result) {
//for example:
std::stringstream ss;
... |
5,115,556 | 5,115,558 | C++: using namespace and #include | In C++ what is the difference between the #include directive and using namespace? Also do you store your namespaces as separate files and what is the file extension for such files?
| In order to answer your question, I will go a little back and take some basics of C and C++.
When compiling C/C++, the compiling the source files into an actual executable is actually two steps, compiling and linking. The compilation step takes one .cpp file at a time and compiles this. The contents of other .cpp files... |
5,115,649 | 5,128,021 | Changing MAC address, through registry does not work | i am using visual studio 2010 and Windows XP on a macbook through bootcamp.
I realized that i could not change the MAC address through the registry(through RegSetValueEx), if my adapter selected is the one integrated to the laptop, Eg: Broadcom wireless adapter for macbook.However certain values like AA-BB-CC-DD-EE-FF... | Thanks to your answer I managed to solve the problem. AA-BB-CC-DD-EE-FF-GG works because of a big luck. The idea is that Windows 7 imposes some restrictions, as you can se on the Wikipedia page: http://en.wikipedia.org/wiki/MAC_spoofing . So, "Under Windows 7, the possible range of spoofed addresses that can be set is ... |
5,115,696 | 5,115,730 | C++ constructor and Qt | There is a statement in the foudations of Qt Development book that goes as follows:
MyClass::MyClass(const string& test, QObject *parent) : QObject( parent )
What is meant when we put : QObject( parent )?
Thanks.
| Are you sure that there aren't two constructor declarations? The : QObject(parent) is an initializer list; it is initializing the base class QObject with the QObject::QObject(QObject*) constructor.
|
5,115,771 | 5,116,058 | VOIP C++ Programming | I want to write a program to create VOIP application for my final year project. For this time being, I spend my time to understand how SIP works and later I need to implement it into my project. As far as i know, the protocol requirement to build this project are:
UDP
RTP
As for my project, it doesn't requires me to ... | Maybe these will be helpful to look at:
Open source RTP library:
jrtplib:
Open source RTSP, RTP with a SIP client AFAIR:
liveMedia
Open source SIP library: reSIProcate
|
5,115,814 | 5,115,840 | GDB is showing 1 Thread in non threaded application | I was debugging my app with gdb.
I used break main
So it can break when main is called.
Know if I use thread info it shows that thread count is 1.
How a thread is starting before main ?
I don't have any thread call in my call so from where thread is getting created. I am using these libs
sqlite , curl , pcre , c... | All programs have at least 1 thread, the main thread. The program is started before main since the C++ runtime does some initializing before main() starts, like calling all global objects which have constructors.
|
5,115,872 | 5,116,417 | What is the best way to evaluate mathematical expressions in C++? | What is the best way to evaluate any custom math expression, for example
3+sqrt(5)+pow(3)+log(5)
I know that embedding Python into C++ can do that; is there any better way?
Thanks!
| Boost.Spirit is a C++ parser library.
Examples:
in its distribution: classic version and current version (look for "calc");
on Rosetta wiki;
some applications using it.
|
5,115,900 | 5,116,007 | Confusion on CreateMutex | Let says I call CreateMutex.
HANDLE h;
h=CreateMutex(NULL, TRUE, NULL);
waitforsingleobject(h, INFINITE);
////Random Code
ReleaseMutex(h);
Assuming I have multiple threads running, the first thread to reach the function createmutex essentially blocks all the other threads from the //random code section until release m... | It doesn't, because you have created an unnamed mutex (the third parameter is the name). Assuming the example code is run in multiple threads, each thread will create a new unnamed mutex, and will promptly get access to the critical section (Random Code), because they are only waiting for their own mutex.
To fix this, ... |
5,116,151 | 5,307,591 | How to get user data for aio signal handler in Mac OS X | I am attempting to use the aio_* functions for asynchronous file IO under Mac OS X, but I am having problems with getting some form of user data into the signal handler.
This is the code that sets up an operation:
class aio_context {
public:
aio_context(int fildes, boost::uint64_t offset,
const MyBufferClas... | Mac OS X does not support real time signals ([RTS] in the posix specification), which is the section of POSIX which adds userdata pointers to signals. This makes Mac OS X very hard to use efficiently with AIO. Your only option is to loop through all your outstanding jobs and handle the ones that are complete.
|
5,116,188 | 5,116,310 | c++ for loop optimization question | I have the following looking code in VC++:
for (int i = (a - 1) * b; i < a * b && i < someObject->someFunction(); i++)
{
// ...
}
As far as I know compilers optimize all these arithmetic operations and they won't be executed on each loop, but I'm not sure if they can tell that the function above also returns the s... | If a function resides within the same compilation unit as its caller, the compiler can often deduce some facts about it - e.g. that its output might not change for subsequent calls. In general, however, that is not the case.
In your example, assigning variables for these simple arithmetic expressions does not really ch... |
5,116,333 | 5,998,752 | dynamic_cast failed when hiding symbol | I have many static libraries. One is static_lib_a.a. I create a dynamic library, dynamic_lib.so to put them together.
In static_lib_a.a, it uses xerces 3.1.1 to parse xml. The following is the code snippet in static_lib_a.a
xerces::DOMElement *pElementNode = dynamic_cast<xerces::DOMElement *>(pNode);
The type of pNode... | The root of your problem is described on the gcc wiki under the section entitled "Problems with C++ exceptions". Make sure you follow the "vague linkage" link there and read the sections on virtual tables and typeinfo.
This all applies to your case because the classes xerces::DOMNode and xerces::DOMElement contain no n... |
5,116,402 | 5,120,630 | Some clarification needed abous Boost asio asynchronous operations and timers | There are one aspect of the timers in asynchronous connections I want to know if I understand correctly.
Suppose that we set a timer before performing a read operation, which includes a handler, and then, run() the io_service.
As I have understood, the io_service ends as soon as the manager ends after being invoked, wh... |
The question is: What happens to that
timer? Do we need to finish it.
The timer's handler will still be invoked if you do not cancel it
void my_read_handler() {
dTimer_.cancel(); // remember to catch exceptions
}
The async_wait handler will be passed an error code of boost::asio::error::operation_aborted if i... |
5,116,440 | 5,120,304 | How to build Notepad++ 5.8.7 from its source | Basically i want to modify auto complete syntax functionality in notepad++. I want to know how to build it using it source code.
| I've got a friend called Google. He told me to look here:
http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Compiling_Notepad%2B%2B#Build_Notepad.2B.2B_v5.8.7_.28win32.2C_Debug.29:
|
5,116,459 | 5,118,379 | Problem with hidden QMainWindow: application crashes after QMessageBox is displayed | // main.cpp
#include <QApplication>
#include "mainwindow.h"
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
MainWindow* window = new MainWindow();
window->show();
return app.exec();
}
// mainwindow.cpp
#include <QTimer>
#include <QMessageBox>
#include <iostream>
#include "mainwind... | The issue seems to be the following: When the dialog box is closed, the application thinks that there are no more windows open (setQuitOnLastWindowClosed refers to visible top-level windows), so it quits. The destructor of your window is not called because you never delete the object!
This should print out the message:... |
5,116,511 | 5,116,781 | When does EnumDisplayMonitor return? | I am using EnumDisplayMonitor to retrieve information about the displays connected to a system. Calling EnumDisplayMonitor requires that a callback function is provided which is then invoked to receive details of each enumerated monitor. My question is when does EnumDisplayMonitor return? Is it immediately or does it b... | It returns when it has finished calling your callback functions. So the sequence of events looks like this:
Enter: EnumDisplayMonitor
Callback: MonitorEnumProc
Callback: MonitorEnumProc
Callback: MonitorEnumProc
...
Leave: EnumDisplayMonitor
All the Windows API routines of this ilk behave this way, e.g. EnumPr... |
5,116,541 | 5,116,618 | Difference between creating object with () or without | i just run into the problem
error: request for member ‘show’ in ‘myWindow’, which is of non-class type ‘MainGUIWindow()’
when trying to compile a simple qt-application:
#include <QApplication>
#include "gui/MainGUIWindow.h"
int main( int argc, char** argv )
{
QApplication app( argc, argv );
MainGUIWindow myWi... | The other answers correctly state that the parentheses version is actually a function declaration. To understand it intuitively, suppose you wrote MainGUIWindow f(); Looks more like a function, doesn't it? :)
The more interesting question is what is the difference between
MainGUIWindow* p = new MainGUIWindow;
and
Mai... |
5,116,642 | 5,125,824 | How to update a Borland 6 C++ Project from including indy.bpi to indy60.bpi? | I develop with Borland Builder 6 in C++.
And when I click on "Components" / "Installer des paquets",
I see the Package dclIndy60.bpi : "Internet Direct (Indy) for D6 Property and Component Editors", meaning for me that it's all ok, I use as wished the Indy60 package (in an Indy9 folder : version 9 for indy dated of nov... | You need to edit the project's .bpk file in Notepad or other text editor. You can then change the package references as needed.
|
5,116,756 | 5,116,923 | Difference between pointer and reference as thread parameter | This is the example:
#include<iostream>
#include<thread>
using namespace std;
void f1(double& ret) {
ret=5.;
}
void f2(double* ret) {
*ret=5.;
}
int main() {
double ret=0.;
thread t1(f1, ret);
t1.join();
cout << "ret=" << ret << endl;
thread t2(f2, &ret);
t2.join();
cout << "ret=" << ret <... | The constructor of std::thread deduces argument types and stores copies of them by value. This is needed to ensure the lifetime of the argument object is at least the same as that of the thread.
C++ template function argument type deduction mechanism deduces type T from an argument of type T&. All arguments to std::thr... |
5,116,763 | 5,133,048 | Transactional, in-memory, object/key/value storage library? | I have a C++ application whose in-memory data set consists of a set of objects, each of which has a key/value set attached. Objects and keys are referred to by an int id, and values are always instances of a single class. Key ids are unique in an object, objects ids are unique in the universe.
This is almost a map<pair... | What you are really after is an exception safe container.
Read these:
http://www.boost.org/community/exception_safety.html
http://lmzr.perso.neuf.fr/attic/Exception_Safe_Generic_Containers.pdf
http://www.drdobbs.com/184401771;jsessionid=TTP1SXYYVJZPLQE1GHPCKH4ATMY32JVN
Your problem quickly reduces to ensuring specific ... |
5,117,171 | 5,117,504 | Output a nice "block" character with ncurses and C++? | I'm writing a console app in c++ using ncurses and I'd like to output a solid ascii block. It'd basically tape up all of the area that would normally be reserved for white space of a normal character. Is there an ASCII character I'm missing or a library function I haven't seen in the manual?
| ASCII is only 7-bit. If you are willing to go with 8-bit, there is the Code Page 437:
http://en.wikipedia.org/wiki/Code_page_437
Then there is Unicode, which opens a whole new world of characters...
|
5,117,448 | 5,117,596 | Creating a strongly-named managed (/clr) C++ assembly | I have a managed C++ assembly using the /clr switch that I am trying to sign as per this question with the following post-build step:
sn -Ra "$(TargetPath)" MyKey.snk
However this is giving the following error:
C:\Path\Assembly.dll does not represent a strongly named assembly
What is going wrong?
| Have you marked the assembly for delay signing in AssemblyInfo.cpp?
[assembly:AssemblyKeyFileAttribute("MyKey.snk")];
[assembly:AssemblyDelaySignAttribute(true)];
|
5,117,519 | 5,139,969 | Googlemock: How to verify elements in an array in an object? | I have a small class:
struct Command
{
uint8_t cmdId;
uint8_t len;
uint8_t payload[MAX_PAYLOAD];
};
And I want to verify only the first two elements of the payload using a googlemock expectation. I can't use ElementsAreArray because that checks that the lengths of the payload and the expectation are the s... | I have received this solution from Piotr Gorak via the googlemock mailing list, discussion here.
MATCHER_P2(CheckFirstTwo, first, second, "Checks the first two elements of an array")
{
return arg[0] == first && arg[1] == second;
}
And in the test I verify like this:
EXPECT_CALL(mockQueue, sendFromIsr(
Poin... |
5,117,563 | 5,117,592 | Use of unary plus operator | I've heard it is used as overloaded operator+ for example
class MyClass
{
int x;
public:
MyClass(int num):x(num){}
MyClass operator+(const MyClass &rhs)
{
return rhs.x + x;
}
};
int main()
{
MyClass x(100);
MyClass y(100);
MyClass z = x + y;
}
Is this really the use of unary pl... | This is not overloading and using unary + .. You need to either make that a free function or make the member function take 0 arguments
class MyClass
{
int x;
public:
MyClass(int num):x(num){}
MyClass operator+() const
{
return *this;
}
};
int main() {
MyClass x = 42;
+ x;
}
|
5,117,661 | 5,117,725 | AccessViolationException from c# when calling a function defined in a c++ library | We have a C++ library where some methods are defined and exported and are being used by our .NET (V 3.5) application. In the c++ library, a function is defined as below
int DLLEXPORT RunAnalysis(long *time, long handle, int *Status)
{
// some code...
}
in .Net assembly
Declaration
[DllImport("wt3145.dll")]
private s... | try
[DllImport("wt3145.dll")]
private static extern int RunAnalysis(ref int Time, int Handle, ref int status);
long in C++ is not the same as long in C#.
|
5,117,844 | 5,117,917 | C++ stringstreams with std::hex | I am looking into code at work. I am having following code. In following code what is the meaning of the last statement?
bOptMask = true;
std::string strMask;
strMask.append(optarg);
std::stringstream(strMask) >> std::hex >> iMask >> std::dec;
In addition to the above question: I have string input and I need to know h... | The last statement creates a temporary stringstream and then uses it to parse the string as hexadecimal format into iMask.
There are flaws with it though, as there is no way to check that the streaming succeeded, and the last stream achieves nothing as you are dealing with a temporary.
Better would be to create the str... |
5,118,115 | 5,120,372 | Unresolved external in .obj files concerning FreeType library class destructors T::~T | After having solved in a more or less good manner this problem :
How to update a Borland 6 C++ Project from including indy.bpi to indy60.bpi?
... I now meet another difficulty :
I now have "unresolved external" destuctors in .obj files :
I have allready seen this error before :
it seems to be a question of virtual dest... | I have not worked with FreeType yet, but I guess the destructors are defined directly inside the class declaration. This means they are implicitly declared as inline. Depending on your compiler, this will prevent the destructors from being included with external linkage in any of the library files generated.
What to do... |
5,118,125 | 5,118,208 | How to convert my project to become a multi threaded application | I have a project and I want to convert it to multi-threaded application. What are the things that can be done to make it a multi threaded application
List out things to be done to convert into multithreaded application
e.g mutex lock on shared variables.
I was not able to find a question which list all those under sing... | Single threaded application need not be concerned about being thread safe.
This issue arises when you have multiple threads which are trying to access a commonly shared resource. At that time, you must be concerned.
So, no need to worry.
EDIT (after question been edited ) :
You need to go through the followin... |
5,118,158 | 5,119,385 | Using SSE to speed up computation - store, load and alignment | In my project I have implemented basic class CVector.
This class contains float* pointer to raw floating point array.
This array is allocated dynamicly using standard malloc() function.
Now I have to speed up some computation using such vectors. Unfortunately as the memory isn't alocated using _mm_malloc() it is not al... | Reading unaligned SSE values is extraordinary expensive. Check the Intel manuals, volume 4, chapter 2.2.5.1. The core type makes a difference, i7 has extra hardware to make it less costly. But reading a value that straddles the cpu cache line boundary is still 4.5 times slower than reading an aligned value. It is t... |
5,118,308 | 5,118,436 | How to convert std::wstring to numeric type(int, long, float)? | What's the best way to convert std::wstring to numeric type, such as int, long, float or double?
| Either use boost::lexical_cast<>:
#include <boost/lexical_cast.hpp>
std::wstring s1(L"123");
int num = boost::lexical_cast<int>(s1);
std::wstring s2(L"123.5");
double d = boost::lexical_cast<double>(s2);
These will throw a boost::bad_lexical_cast exception if the string can't be converted.
The other option is to use... |
5,118,411 | 5,118,446 | Modifying the date and time values using SYSTEMTIME, FILETIME, and ULARGE_INTEGER | I am making a program, in C++ using Visual Studio 2005, that needs to create a watermark with the time on a set of images.
These images are taken from a video that were processed at certain time intervals. What I am trying to do is to modify the time on each image through SYSTEMTIME. I looked at the MSDN and it says no... | They suggest converting SYSTEMTIME to FILETIME, which is a number of ticks since an epoch. You can then add the required number of 'ticks' (i.e. 100ns intervals) to indicate your time, and convert back to SYSTEMTIME.
The ULARGE_INTEGER struct is a union with a QuadPart member, which is a 64bit number, that can be dire... |
5,118,543 | 5,118,576 | Using References in const Methods | Let's say I have a class like this:
class LinkedList
{
struct Node
{
int StoredValue;
// ...
};
Node& GetNodeReference(std::size_t Index)
{
// ...
return NodeReference;
}
public:
int Get(std::size_t Index) const
{
return GetNodeReference(In... | I'm not sure what you're trying to achieve, but you could provide two overloads of GetNodeReference:
Node& GetNodeReference(std::size_t Index)
{
// ...
return NodeReference;
}
const Node& GetNodeReference(std::size_t Index) const
{
// ...
return NodeReference;
}
Note that the second overload has two... |
5,118,923 | 5,120,347 | Reading data from socket using read function | I am trying to read data using the following code from a socket:
n = read(fd, buffer, 50000);
The question is: when the data from the web server is larger than the tcp package size, these data will be splited into multi packages. In this case, will read function just read one data package from fd, or it will read all ... | Because you are using TCP, your socket is of type SOCK_STREAM. A SOCK_STREAM socket is a byte stream and does not maintain packet boundaries, so the call to read() or recv() will read data that came from multiple packets if multiple packets of data have been received and there is sufficient space in your buffer. It m... |
5,118,976 | 5,119,032 | What's the reason behind applying two explicit type casts in a row? | What's the reason behind applying two explicit type casts as below?
if (unlikely(val != (long)(char)val)) {
Code taken from lxml.etree.c source file from lxml's source package.
| That's a cheap way to check to see if there's any junk in the high bits. The char cast chops of the upper 8, 24 or 56 bits (depending on sizeof(val)) and then promotes it back. If char is signed, it will sign extend as well.
A better test might be:
if (unlikely(val & ~0xff)) {
or
if (unlikely(val & ~0x7f)) {
depend... |
5,119,001 | 5,119,797 | Synchronization after thread end | Because part of this question wasn't addressed, I'm making it a separate question:
#include<iostream>
#include<thread>
using namespace std;
void f2(double* ret) {
*ret=5.;
}
int main() {
double ret=0.;
thread t2(f2, &ret);
t2.join();
cout << "ret=" << ret << endl;
}
Is this program data race free?
... | Your program is data race free. [thread.thread.member]/p5 describes join() with a Synchronization paragraph:
Synchronization: The completion of the thread represented by *this synchronizes
with (1.10) the corresponding successful join() return. [Note: Operations on *this are not synchronized. —endnote]
(1.10) refers t... |
5,119,033 | 5,119,643 | Calling c++ runtime from DllMain or global initializers | The question is inspired by this discussion.
It seems that fears concerning C++ runtime invokations from DllMain (or from global variables ctor's) are sligtly outdated. I'm using global initializers in dlls frequently without any faults, and now I've run a special test program (compiled with VC2010 Express w/o SP) cont... | Getting the CRT initialized while loading a DLL is a very common scenario, it happens for any COM server for example. As such you can rely on the CRT explicitly supporting the scenario, as long as you don't require it to initialize your variables with code that in turn depend on the dangerous api calls. Getting manag... |
5,119,288 | 5,120,984 | Getting fault address that generated a UNIX signal | I am interested in a signal handler which can identify the address of the instruction which caused the problem.
I know about siginfo_t and __builtin_return_address and neither seem to work:
#include <iostream>
#include <signal.h>
void handler (int, siginfo_t *, void *);
int main ()
{
begin:
std :: cerr << &&begin... | The third argument to a handler installed with SA_SIGINFO (the one declared as void *) is a pointer to a ucontext_t structure. The contents of this structure are architecture- and OS-specific and not part of any standard, but they include the information you need. Here's a version of your program adapted to use it (L... |
5,119,495 | 5,119,553 | Delete memory in inheritance | I have code below, it always has memory leak please help me.
Thanks,
Ankata
class ABCD
{
public:
ABCD(void);
~ABCD(void);
CString tem1;
CString tem2;
};
class CDE :
public ABCD
{
public:
CDE(void);
~CDE(void);
CString tem;
};
void main()
{
CList<ABCD*> m;
CDE *a = ne... | Your destructor for class ABCD is not virtual so by casting the pointer to base class type, it will not call the destructor of the derived one thus not freeing memory allocated in CDE.
|
5,119,581 | 5,130,320 | Accessing body (at least some data) in a iframe with IE plugin Browser Helper Object (BHO) | I'm developing an IE8+ BHO plugin. For now I'm simply trying to insert a text into an iframe (class="Al Ai Editable") contained in another iframe (id="canvas_frame").
I managed to obtain the IHTMLElement of the iframe i want to add text to (the class="Al Ai editable"). I can prove this by the fact that the el variable... | The reason for the error is a security restriction. You're accessing a nested iframe so you'll need to reconfigure your function to work recursively to bypass the restriction.
See how you access the first level of iframes using
hr = pContainer->EnumObjects(OLECONTF_EMBEDDINGS, &pEnumerator);
but then use
doc->getEle... |
5,119,963 | 5,120,085 | Return stringstream from a function | Clearly I am missing something important about stringstreams in general here, but could someone explain why
#include <sstream>
using namespace std;
stringstream foo() {
stringstream ss;
return ss;
}
Fails with
In file included from /usr/include/c++/4.4/ios:39,
from /usr/include/c++/4.4/ostream:40,
... | After correct the type-o in the return type (noted by Mahesh), your code will not compile in C++03 because stringstream is not copyable. However if your compiler supports C++0x, turning that on allows your code to compile because stringstream is MoveConstructible.
|
5,120,303 | 5,124,519 | invalid option value exception using boost program-options | I have a Visual Studio 2008 C++ application using boost v1.45.0 program-options.
I would like to be able to parse a command-line option that looks like this: foo.exe -x 1,2, 4-7 such that it produces a std::vector< int > with the values [1, 2, 4, 5, 6, 7]. So, I've written a custom validator:
typedef std::vector< int >... | The typedef std::vector<int> as a boost::program_options::value_semantic does not work the way you desire because a vector has a special meaning to the program options library:
The library provides special support
for vectors -- it will be possible to
specify the option several times, and
all specified values wi... |
5,120,552 | 5,120,589 | c++ design question try catch | I have the following code in which dbh constructor may throw exception. The question I have is, dbh is declared inside try block. Will it be available after the catch? If yes, are there any other exceptions where the scope resolution is different than {} ? If not, what is the best design alternative?
status func(const ... |
Will it be available after the catch?
No. It will be destroyed at the end of the block in which it is declared, just like any other local variable.
try {
dbhandler<recType> dbh(("dbName"),("table"));
} // dbh.~dbhandler<recType>() is called to destroy dbh
What is the best design alternative?
Declare dbh ou... |
5,120,816 | 5,120,845 | Type mismatch using template in C++ | I've written a class template (in the file abc.hpp):
template <class Node>
class Edge {
public:
Edge(Node n1, Node n2):_start(MIN(n1,n2)),_end(MAX(n1,n2)) {};
Node GetStart ()const {return _start;}
Node GetEnd ()const {return _end;}
friend std::ostream& operator<<(std::ostream& os, const Edge<Node>& ed)... | You're trying to assign the function to vstart, instead of the result of calling the function:
int vstart = my_var.GetStart(); // <- I added () here
int vend = my_var.GetEnd(); // <- and here.
|
5,120,861 | 5,120,880 | How to measure memory usage from inside a C++ program? | Is it possible, for a c++ program, to track how much memory the program is using at one time?
For example, a function with a prototype:
int getEstimatedTotalMemoryUsage();
I suppose if it's not possible, then one will have to get out of the program, do a system call and check the results from there. If so, what tools ... | Yes - use POSIX getrusage. From the Linux man page:
Synopsis
#include <sys/time.h>
#include <sys/resource.h>
int getrusage(int who, struct rusage *usage);
Description
getrusage() returns current resource usages, for a who of either RUSAGE_SELF or RUSAGE_CHILDREN. The former asks for resources used by the current pr... |
5,121,333 | 5,121,412 | How do I get Doxygen to expand macros from include files? | I have a number of multiline macros defined in a file called macros.h. In my doxyfile, I've got
ENABLE_PREPROCESSING = YES
MACRO_EXPANSION = YES
EXPAND_ONLY_PREDEF = NO
PREDEFINED =
EXPAND_AS_DEFINED =
SKIP_FUNCTION_MACROS = NO
yet Doxygen still will not expand the macros in any source ... | You've told your compiler about your include path, but you haven't told doxygen. So it tries to open "macros.h" and gets a file-not-found error.
You need to properly set INCLUDE_PATH in your Doxyfile.
|
5,121,782 | 5,121,800 | Can Non-static function modify a static variable in c++ | can Non-static function modify a static variable in c++
| Yes, a non-static member function can modify a static data member as long as the data member's visibility allows it.
|
5,121,834 | 5,122,500 | Light on everything is gone directx | When I turn of light. I can see my object but with out the 3D light.
I set my object position to this 0, 0, 10.
Here is my code to set up my Light
D3DLIGHT9 light;
ZeroMemory( &light, sizeof(D3DLIGHT9) );
light.Type = D3DLIGHT_DIRECTIONAL;
light.Diffuse.r = 1.0f;
light.Diffuse.g = 1.0f;
light.Diffu... | We can't possibly tell you exactly what the problem is without a more complete source listing. Having said that, I have an idea.
Check the normals on your object. If your normals are incorrect, turning on lighting might cause the object to render as black, which may make it disappear if your background is black.
|
5,121,913 | 5,121,953 | Qt and image processing | How can someone use Qt for image processing? Are there libraries or plugins for Qt for this purpose?
Thanks.
| Qt is rather meant for developing graphical user interfaces (GUIs). However, it comes with a lot of supplementary libraries, including one dedicated to image processing. However, if you want to get serious, I would recommend a dedicated library such as OpenCV.
|
5,121,942 | 5,122,344 | Full path names printed for __FILE__ in VS2008 | Our code uses __FILE__ to print code locations in a log file.
Our intent is for all instances of __FILE__ to print the filename ONLY, no path.
However, we just noticed that while source (.cpp files) correctly print just the filename, the headers (.h files) print the full path. This exposes our build server's path on c... | This is asserted as "by design" in this feedback article. Consider a post-processing step that hacks the paths the way you want them.
|
5,122,065 | 5,122,155 | Should I use openCV for image processing in c++? | Do you recommend using OpenCV for doing image processing using C++?
Thanks.
| It depends on what you mean by image processing.
If you are talking about changing the image; like compressing it or resizing it, then no not at all. I would use imagemagick.
If you want to analyze images; like trying to see if they contain something like a face, or a hand. Generally speaking open CV is great for teac... |
5,122,297 | 5,122,331 | C++ - Image processing library or a computer vision one? | I'm interested in performing feature extraction using C++ for medical images (i.e; malignant and benign nodules).
What is suitable for me, an Image processing library or a computer vision one?
Thanks.
| If you want to do feature extraction you should look more into computer vision libraries. Image processing is more in the of the kind of algorithms Photoshop does, i.e. to enhance/improve/transform images, not the retrieval of information out of them. The terms are sometimes uses synonymously though.
You might want t... |
5,122,384 | 5,122,801 | PHP & C++ Retrieving user IP | I have a C++ console app that uses wininet.h to go out to a URL, and download the contents of a web page.
The contents are usually just a single IP address. It goes here: http://www.whatismyip.com/automation/n09230945.asp
Everything works great.
Then I decided to create my own IP checker in PHP, using the following cod... | cout will expect a string to be null-terminated. Because you're just reading bytes into a buffer, and not null-terminating them at the end, cout will carry on past the end of the bytes you've read and just carry on dumping memory out until it hits a null pointer or memory protection kicks in.
With your code, what's hap... |
5,122,417 | 5,122,436 | Not compiler optimizing portions of code in C++ | Is there a way to tell the compiler to not optimize selective portions of code? I know you can tell the compiler to not optimize away certain variables using volatile but what about entire chunks of code?
| In most cases, yes, but the exact method depends on your particular compiler.
Typically it will be something like:
#pragma optimize(off)
Anything optimizer-related is completely outside the scope of the standard. The only part the standard plays is in mandating the behavior, but the compiler can do any optimizations ... |
5,122,447 | 5,122,576 | Does exit(0) pose any issues in MFC? | I want to immediately exit my MFC app in C++. Is exit(0) the best solution? eg. does it prevent destructors from being called, is it threadsafe? etc. Is there a better solution? Thanks.
| Yes, exit(0) is the best solution. It will cause the destructors of global objects (and static objects within functions) to run, however it will not cause destructors of stack-allocated or heap-allocated objects to run:
// At global scope
ClassWithDestruct globalObject;
void SomeFunction()
{
static ClassWithDestr... |
5,122,671 | 8,630,163 | Using Google Chromium's Views Project as an Application Framework in C++ | I have had contact with Google Chromium Code and that’s terrific for building applications with. The problem now lies that no-one has tried to use it outside Google Chromium Project. What I have in mind is to develop an open source project which may be used for this purpose. The fundamental goals would be:
Guarantee L... | see https://github.com/lianliuwei/chromium_base
I create it for the same reason like you.
chromium is great project. It's code could be useful to using in other project. but It need time to extract it. I see one project to extract the ui part, but it change too many for noreason for example it change the .cc to .cpp. ... |
5,122,831 | 5,123,027 | C++ constructor syntax explaination | I was going through a tutorial for building an AST with the help of Clang/LLVM.
I see this syntax there:
struct PPContext {
// Takes ownership of client.
PPContext(clang::DiagnosticClient* client = 0,
const std::string& triple = LLVM_HOSTTRIPLE)
: diagClient(client == 0?new clang::TextDiagnosticPrin... | These are constructor initializers. They initialized class members with the value given to them. For instance:
class TestClass
{
private:
int someField;
public:
TestClass() : someField(5) { }
};
Will initialize the member someField to have a value of 5 during the call to the TestClass() constructor. You ca... |
5,122,875 | 5,123,225 | AIR NativeProcess API | I use nativeprocess api in AIR to launch a c++ console app. The console app runs correctly but does not appear, but I want it to be visible and user be able to interact with it. How can I achieve that?
| Instead of launching your executable directly, you'll need to launch your platform's terminal application (on Windows, that's CMD.exe, on OS-X it's Terminal.app, and on unix/linux it's xterm).
By default, the terminal application will run an interactive shell prompt, but you can use command-line arguments to tell it to... |
5,122,925 | 5,142,850 | Why does Doxygen documentation only appear for the last of multiple adjacent groups? | I'm trying to document several similar functions at once using Doxygen groups. I would like the functions to share the same documentation as shown in the example here.
// @{
//! @brief Some documentation
int func1(void);
int func2(void);
// @}
// @{
//! @brief Some other documentation
int func3(void);
int func4(void);... | Solved!
The documentation to be factored out for each function group must precede the opening braces:
//! @brief Some documentation
// @{
int func1(void);
int func2(void);
// @}
//! @brief Some other documentation
// @{
int func3(void);
int func4(void);
// @}
|
5,122,963 | 5,123,069 | Does set::insert saves a copy or a pointer C++ | does the function set::insert saves a pointer to the element or a copy of it. meaning, can I do the following code, or I have to make sure that the pointers are not deleted?
int *a;
*a=new int(1);
set<int> _set;
_set.insert (*a);
delete a;
*a=new int(2);
_set.insert (*a);
delete a;
I gave the example with int, but my ... | All STL containers store a copy of the inserted data. Look here in section "Description" in the third paragraph: A Container (and std::set models a Container) owns its elements. And for more details look at the following footnote [1]. In particular for the std::set look here under the section "Type requirements". The K... |
5,122,983 | 5,123,055 | transfer java to c++ | In Java
public int compareTo2(String that) {
String sig1 = this.sort();
String sig2 = that.sort();
return sig1.compareTo(sig2);
}
In C++
int compareTo2 (string that) {
string sig1 = this.sort();
string sig2 = that.sort();
return strcmp(sig1,sig2);
}
The first is a Java program. I translated it... | Assuming that with string you talk of std::string:
std::string doesn't provide a member named sort. You shall do that with std::sort:
std::sort(sig2.begin(), sig2.end());
And strcmp is thought to be used with const char*s, so you have to write:
return strcmp(sig1.c_str(), sig2.c_str());
Finally, this has to be derefe... |
5,123,014 | 5,123,520 | Memory Leaks During Debug Sessions - Possible Threat? | While programming, I compile and test application maybe hundred of times a day. Moreover, I use to put my computer into sleep mode overnight, so memory does not get cleaned by the fresh system start.
Often, I postpone solving memory leaks for later, say a particular day in a week. My question is, whether memory leaks t... | No, the operating system cleans up when the process terminates.
|
5,123,314 | 5,123,425 | Compile-time checking if right shift is arithmetic on signed types | I am wondering what is the most portable way of checking whether right shift is arithmetic when operating for on signed types (e.g. whether -2 >> 1 is -1) at compile-time.
My idea is to check this somehow on compile time and be able to detect this, so I can compile different versions of the function (depending whether ... | The branch could be avoided by using a preprocessing-time test
#if ((-1)>>1) == (-1))
...
#else
...
#endif
|
5,123,361 | 5,188,422 | Finding "~/Library/Application Support" from C++? | I've written a GTKmm application and I'm trying to create some OS X enhancements. I'd like to store my configuration file in the Application Support/myApp folder, however, I can't figure out the proper way to locate this folder.
I've tried looking through the Core Foundation library (that I'm using to get my myApp.app... | Proper way to do it in C/C++:
#include <CoreServices/CoreServices.h>
FSRef ref;
OSType folderType = kApplicationSupportFolderType;
char path[PATH_MAX];
FSFindFolder( kUserDomain, folderType, kCreateFolder, &ref );
FSRefMakePath( &ref, (UInt8*)&path, PATH_MAX );
// You now have ~/Library/Application Support stored i... |
5,123,387 | 5,123,432 | Loading a BMP into an OpenGL textures switches the red and blue colors. (C++/Windows) | I'm trying to load a bitmap into an OpenGL texture and display it to the screen, but when I do so, the red and blue values seem to switch (e.g.: a blue image appears orange, green images remain unchanged, etc..). This problem only exists when loading bitmaps, I can load .pngs relatively error free.
This is the code I'... | You've got your RGB and BGR backwards.
glTexImage2D(GL_TEXTURE_2D, 0, 3, ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT), \
0, GL_RGB, GL_UNSIGNED_BYTE, ilGetData());
Is there a GL_BGR you can specify on the second line, instead of GL_RGB? That should fix it.
The reason a PNG causes the image to flip ... |
5,123,552 | 5,123,574 | How do i open a file when you know only part of the file name? C++ | I need to be able to open a file when i only know part of the file name. i know the extension but the filename is different every time it is created, but the first part is the same every time.
| You'll (probably) need to write some code to search for files that fit the known pattern. If you want to do that on Windows, you'd use FindFirstFile, FindNextFile, and FindClose. On a Unix-like system, opendir, readdir, and closedir.
Alternatively, you might want to consider using Boost FileSystem to do the job a bit m... |
5,123,641 | 5,156,406 | CDockingManager GetPaneList() causes assertion failure in wincore.cpp? | So I thought this would be pretty simple, but I forgot it's MFC. Instead of registering a notification listener for data model changes that would possibly require a GUI update on each individual control I figure why not register it once and then send a message to all the open dock panes and allow them to update their c... | Here's the obvious workaround that I didn't want to have to do but after hours of debugging and no response here I guess this is a viable answer:
I added std::vector<CDockPane*> m_dockList; to the members of CMainFrame
Now after each call to AddPane in various places that can create and open new dock panes I make a sub... |
5,123,656 | 5,123,687 | Ti-83 Emulator question with the ROM | I have been building knowledge of computers and C++ for quite a while now, and I've decided I want to try making an emulator to get an even better understanding. I want to try making a TI-83 Emulator (runs on a Zilog Z80 CPU). I currently have two problems:
The first is that the "PC" register that points to the current... | There's is most likely a programmable paging register outboard of the processor core that can be set to map a portion of the 256K at a time into part of the 64K address space. You will need to emulate that. Hopefully you can find out about this in official or unofficial documentation. If you have a schematic or PCB i... |
5,123,688 | 5,126,589 | C++ Iterator Pipelining Designs | Suppose we want to apply a series of transformations, int f1(int), int f2(int), int f3(int), to a list of objects. A naive way would be
SourceContainer source;
TempContainer1 temp1;
transform(source.begin(), source.end(), back_inserter(temp1), f1);
TempContainer2 temp2;
transform(temp1.begin(), temp1.end(), back_inse... | EDIT: Working version at http://ideone.com/5GxnW . The version below has the ideas but does not compile. It supports run time type checking, and run time function composition.
The idea is to define a generic (unary) function class, and a way to compose them with run time type checks. This is done with a combination of ... |
5,123,992 | 5,126,527 | Dynamic casts returns null when library with C++ python extensions is used as a plugin on RHEL5 | I have a library with C++ python extensions (C++ calls python which in turn calls C++) using boost::python and python libraries (this is messy, but a lot of it is legacy) which when tested standalone works correctly. In particular, a certain dynamic_cast works correctly.
But when the library is packaged for use as a p... | Take a look at similar question and GCC FAQ
If you use dlopen to explicitly load code from a shared library, you must do several things. First, export global symbols from the executable by linking it with the "-E" flag (you will have to specify this as "-Wl,-E" if you are invoking the linker in the usual manner from th... |
5,123,998 | 5,124,339 | Receiving all data sent with C sockets | If I write a server, how can I implement the receive function to get all the data sent by a specific client if I don't know how that client sends the data?
I am using a TCP/IP protocol.
| If you really have no protocol defined, then all you can do is accept groups of bytes from the client as they arrive. Without a defined protocol, there is no way to know that you have received "all the bytes" that the client sent, since there is always the possibility that a network failure occurred somewhere between ... |
5,124,124 | 5,124,284 | QT4: How to get access to an object what is on mainwidow from an other class? | If Im in mainwindow.cpp then i can get every object on it with:
this->ui->textBox ...
What if there is another class (myclass2.cpp) and I would like to get the value of one the textBoxes. But they are on my mainwindow. I cant use this->ui->textBox
Whats the way to get access to the objects?
Thank You
| In general, this is not a problem specific to Qt. There are several ways you can do this:
Provide a method on mainwindow that encapsulates what you want, and call that from myclass2.
// In mainwindow.cpp:
QString mainwindow::valueOfTheTextEditYouAreInterestedIn() const
{
return ui->textBox->toPlainText();
}
Thi... |
5,124,140 | 5,124,172 | memcpy for class-level array in copy constructor leads to segfault | There is a template class for sequences in 4-letter alphabet (=> 2 bits per letter):
template <size_t _size>
class Seq {
private:
const static size_t _byteslen = (_size / 4) + (_size % 4 != 0);
char _bytes[_byteslen];
public:
Seq() {};
Seq(const char* s);
Seq(const Seq<_size> &seq);
...
std:... | "If copy constructor is implemented as silly from-to-string, then everything works OK."
Seq(const Seq<_size> &seq) {
Seq(seq.str().c_str());
}
Really? Because that constructor doesn't initialize _bytes[] at all. (Instead, it creates a different temporary Seq object, which is unused and immediately destroyed.)
|
5,124,228 | 6,505,415 | C++/sqlite wrapper for dead-easy class serialization? | I am looking for an OO sqlite C++ wrapper which allows quasi-transparent serialization and de-serialization of classes.
The work-flow I have in mind is as follow:
define a class record with the data members
Supply this class to the wrapper which creates a suitable table
Simple serialization and de-serialization via <... | There's no easy C++ ORM (Object Relational Mapping) tools. The two libraries I know of that ease the process are :
SOCI
Debea (EDIT: obsolete)
SOCI is simpler and is boost-like in philosophy, while debea is more ORM oriented.
By the way, if SQLite / SQL / requests are not mandatory, you can use Boost serialization fr... |
5,124,282 | 5,127,820 | Executing slot on every application's event loop iteration | How can I call my slot on every iteration of application's event loop?
Only way I know is to use QTimer and on every timeout (every millisecond) signal I can call my slot.
But I don't like this option, it looks like workaround.
Any suggestions how to do this more correctly?
| From the Qt 4.7 QCoreApplication::exec() documentation:
To make your application perform idle
processing (i.e. executing a special
function whenever there are no pending
events), use a QTimer with 0 timeout.
More advanced idle processing schemes
can be achieved using processEvents().
So your approach is wha... |
5,124,328 | 5,124,674 | Set C/C++ compiler for Python extensions | I would like to setup a default C and C++ compiler when building Python extensions under Linux. I noticed the --compiler option to python setup.py build, but I am wondering if there is a way of setting this as an environmental variable so that I can specify them just once.
| It's not possible to use an environment variable, but you can create a setup.cfg file. See Writing the Setup Configuration File. The following setup.cfg file will try to use the Intel C Compiler:
[build_ext]
compiler=icc
|
5,124,546 | 5,129,306 | SELECT LAST_INSERT_ID() returns 0 after using prepared statement | I am using MySQL and a prepared statement to insert a BLOB record (jpeg image). After executing the prepared statement, I issue a SELECT LAST_INSERT_ID() and it returns 0.
In my code I put a breakpoint after the execution command and in a MySQL command (monitor) window, I issue the SELECT LAST_INSERT_ID() and it ret... | Looks like the issues is with the MySQL C++ connector.
LAST_INSERT_ID() returns 0 when
the ID field is null, explicit
insert.
LAST_INSERT_ID() returns 0 when
the ID field is not specified,
implicit insert.
I tried insert the BLOB (JPEG image) from the command line (monitor), and it works:
mysql> describe picture_im... |
5,124,793 | 5,124,808 | usage of void pointer in c/c++ | Hey, I am wondering how void pointers is applied in the real world in terms of making a software more secure, more flexible.
For example, I know that void pointers, what pointer it will cast to is hidden to outside, which will make a software more secure.
Are there other reasons why you would use void pointers?
| Void pointers don't make the software any more secure.
The reason to use void* in c is a form of polymorphism - if you don't know what type the data will be you can pass a void*
In C++ there is less need to use void* and the language prevents some of the C uses
|
5,124,939 | 5,124,978 | C++ using TABS spacing | I am trying to make a cout<<intRate<<"\t\t"; statement start out in different position then cout <<"\t\t"<<monPayment;. My problem is aligning rate and payment values.
What I am getting for the output:
Principal Interest Rate
0.07 0.075 0.08 0.085 0.09 0.095 0.1
_________________________... | It's difficult to tell from your question, but it sounds like you're looking for iomanip.
#include <iostream>
#include <iomanip>
int main()
{
std::cout << setw(4) << 1 << setw(4) << 2 << std::endl;
}
Output:
1 2
|
5,124,989 | 5,125,117 | Brute Force Character Generation in C++ | So I'm trying to make a brute force string generator to match and compare strings in CUDA. Before I start trying to mess around with a language I don't know I wanted to get one working in C++. I currently have this code.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int sLength = 0;
i... | You basically just need to increment a counter, than convert the count number to base (size of char array)
Here's an example which does normal numbers up to base 16.
http://www.daniweb.com/code/snippet217243.html
You should be able to replace
char NUMS[] = "0123456789ABCDEF";
with your set of characters and figur... |
5,125,041 | 5,125,110 | How to calculate a SHA-512 hash in C++ on Linux? | Is there a standard library or commonly used library that can be used for calculating SHA-512 hashes on Linux?
I'm looking for a C or C++ library.
| Have you checked OpenSSL. I myself have not used it but documentation says it supports it.
Here is list of few more implementations.
Example code
md = EVP_get_digestbyname("sha512");
EVP_MD_CTX_init(&mdctx);
EVP_DigestInit_ex(&mdctx, md, NULL);
EVP_DigestUpdate(&mdctx, mess1, strlen(mess1));
EVP_DigestUpdate(&mdct... |
5,125,241 | 5,125,321 | how to make an application thread safe? | I thought thread safe, in particular, means it must satisfy the need for multiple threads to access the same shared data. But, it seems this definition is not enough.
Can anyone please list out the things to be done or taken care of to make an application thread safe. If possible, give an answer with respect to C/C++ l... | There are several ways in which a function can be thread safe.
It can be reentrant. This means that a function has no state, and does not touch any global or static variables, so it can be called from multiple threads simultaneously. The term comes from allowing one thread to enter the function while another thread i... |
5,125,286 | 5,125,366 | One problem with read function in c++ | I am using read function to read data from a socket, but when the data is more than 4k, read function just read part of the data, for example, less than 4k. Here is the key code:
mSockFD = socket(AF_INET, SOCK_STREAM, 0);
if (connect(mSockFD, (const sockaddr*)(&mSockAdd), sizeof(mSockAdd)) < 0)
{
cerr << "Error con... | This is by design and to be expected.
The short answer to your question is you should continue calling "read" until you get all the data you expect. That is:
int total_bytes = 0;
int expected = BUFSIZE;
int bytes_read;
char *buffer = malloc(BUFSIZE+1); // +1 for null at the end
while (total_bytes < expe... |
5,125,342 | 5,125,363 | CreateMutex Confusion | So I have called createmutex like so
while(1){
HANDLE h;
h=CreateMutex(NULL,TRUE,"mutex1");
y=WaitForSingleObject(h,INFINITE);
///random code
ReleaseMutex(h)
}
It runs fine after looping twice, but deadlocks on WaitForSingleObject (h,INFINITE) after the third loop. This is with two threads ru... | You're waiting on a mutex that's already owned... please don't do that.
Also, you're not destroying the mutex, only releasing it. The next call should give you ERROR_ALREADY_EXISTS. The complete quote from MSDN is "If the mutex is a named mutex and the object existed before this function call, the return value is a h... |
5,125,408 | 5,125,535 | C++0x: how to get variadic template parameters without reference? | Given the following contrived (and yes, terrible) example:
template<typename... Args>
void something(Args... args)
{
std::tuple<Args...> tuple; // not initializing for sake of example
std::get<0>(tuple) = 5;
}
It works if you call it like so:
int x = 10;
something<int>(x);
However, it does not work if you cal... | I don't understand your question. This code works fine with GCC and I see no reason why it shouldn't work.
#include <tuple>
template<typename... Args>
void something(Args... args)
{
std::tuple<Args...> tuple{args...};
std::get<0>(tuple) = 5;
}
int main() {
int x = 10;
something<int&>(x);
}
[js@HOST2 cpp]$ g+... |
5,125,511 | 5,125,587 | std::vector.size() not working | I have some code involving some vectors, but it refuses to give me the size of the vector:
using namespace std;
struct key_stat{
string USER, url;
float click_count, post_count, click_cost, post_cost;
keyword_stat(): USER("") {}
};
class key
{
private:
string word;
vector <key_stat> stats;
pub... | vector's operator[] does not do bounds checking. So, here's what happens:
for (x = 0; x < keywords.size(); x++){
if (keywords[x].get_word() == word)
break;
}
if this doesn't find your word in the keywords vector, x will be the size of keywords.
vector <keyword_stat> t = keywords[x].get_stats();
a piece a... |
5,125,896 | 5,125,914 | How to disassemble a binary executable in Linux to get the assembly code? | I was told to use a disassembler. Does gcc have anything built in? What is the easiest way to do this?
| I don't think gcc has a flag for it, since it's primarily a compiler, but another of the GNU development tools does. objdump takes a -d/--disassemble flag:
$ objdump -d /path/to/binary
The disassembly looks like this:
080483b4 <main>:
80483b4: 8d 4c 24 04 lea 0x4(%esp),%ecx
80483b8: 83 e4 f0 ... |
5,126,206 | 5,128,998 | Memory allocation problem | I'm writing a Windows Service that allocates memory dynamically. I tried both c++'s new operator and C's malloc. They return (probably valid) pointer but when I try to dereference it the program crashes with Windows saying:
The instruction at "0x77c478ac"
referenced memory at "0x00cb9001". The
memory could not be ... | It's pretty funny, you have the answer commented in your code. recv returns -1, indicating that no bytes were read and there is an error, (why not check errno and see what the problem is?) and then you call regexp_cmp anyway on an uninitialized buffer. No wonder it crashes.
As a second point, your code it overly compl... |
5,126,219 | 5,126,331 | Is there a reference_wrapper<> for rvalue references? | I wonder how the following can be done
void f(string &&s) {
std::string i(move(s));
/* other stuff */
}
int main() {
std::string s;
bind(f, s)(); // Error.
bind(f, move(s))(); // Error.
bind(f, ref(s))(); // Error.
}
How can I pass an rvalue reference and store it as an rvalue reference (possibly wr... | My take on this.
20.8.10.1.2/10 in N3225
The values of the bound arguments v1, v2, ..., vN and their corresponding types V1, V2, ..., VN
depend on the types TiD derived from the call to bind and the cv-qualifiers cv of the call wrapper g as
follows:
if TiD is reference_wrapper, the argument is tid.get() and its t... |
5,126,253 | 5,126,303 | Difference in implementation of malloc and new. Stack implementation? | While allocating memory, the new operator throws an exception if the memory is not available. On the other hand, malloc returns a NULL. What is the reason for the difference in implementation. Also, on static memory allocation, i.e. on the stack, is there an exception if we run out of memory?
I have already gone throug... | The problem with C code is that you are supposed to check the return value of function to make sure they worked correctly. But a lot of code was written that did not check the return value and as a result blew up very nicely when you least expected it.
In the worst case scenario it does not even crash immediately but c... |
5,126,294 | 5,127,107 | QWebView doesn't load any external resources if it loads a html-file from qresources | As described in the title my problem is that qwebview doesn't load a html file correctly if it resides in my resources. It loads it perfectly if I load it from outside of the resources as normal local file. But this is not an option for me. I would like to bundle the file with the application.
EDIT: By the way, I'm tal... | Please take a look at the second parameter of
void QWebView::setHtml ( const QString & html, const QUrl & baseUrl = QUrl() )
According to documentation:
External objects such as stylesheets
or images referenced in the HTML
document are located relative to
baseUrl.
Below is code that works for me.
#include <QtC... |
5,126,425 | 5,126,436 | How to Show windows side by side from c++? | everyone the question is how to use options Show windows side by side by side from c++? I use windows 7 professional, 64 bit, is there some function that can be used, to switch widow?
| You have to do this yourself. Work out the coordinates of the windows based on the size of the work area. Divide the width by 2 and do the math. There are no in-built shortcuts.
I don't understand your other question about switching window.
|
5,126,518 | 5,126,572 | about power of sizeof operator in C++ | I am reading Modern C++ design. It was mentioned about sizeof opeator as following description. Following paragraph is explained from generic programming point of view.
There is a surprising amount of power in sizeof: You can apply sizeof to any expression, no matter how complex, and sizeof returns its size without ac... |
what does author mean sizeof returns its size with out actually evalutating the exression at runtime.
It means that sizeof(1/0) will yield sizeof(int), even though 1/0 would normally abort the program, because division by zero is a runtime error. Also, for any p declared as T* p, sizeof(*p) will yield sizeof(T) no ma... |
5,126,541 | 5,126,640 | pointer (ref to structure) as an argument for a function to assign value | I am a newbie in programming and apologise in advance if my question is too silly.
My c++ project is compiled as library .xll (DLL for excel), the framework code (program entry point) is coded correct and work stable. Custom functions are separate modules.
// header.h
typedef struct _TMDYDate {
long month;
lo... | It seems like you call the function from a place where its declaration isn't visible. If you do, the compile does not know what types the parameters should have so it passes them all as ints.
Functions called from another .c file should be declared in the corresponding .h file,and included in all .c files using the fun... |
5,126,608 | 5,126,624 | Who is right and who is wrong aka GCC vs Visual Studio | This code (doesn't "work" correctly) but compiles in VS 2010 but doesn't won't to compile in GCC 4.5.1
#include <iostream>
#include <vector>//not necessary second > should skip like brackets
using namespace std;
template<class ForwardIterator>
void iterator_swap(ForwardIterator& left,ForwardIterator& right)
{
typ... | The problem is here:
iterator_swap(v_1.begin(),v_2.begin());
You're passing a temporary (returned from the begin() functions) to a function that accepts two non-const references. Standard C++ prohibits temporaries from binding to non-const references. (Standard C++ does allow temporaries to bind to const references, h... |
5,126,631 | 5,126,853 | Basic question about C++ memory management | // main.cpp
class Cat()
{
public:
Cat()
{
a = 0;
(*b) = 0;
}
int a;
int* b;
};
int main(int argc, char* argv[])
{
Cat cat1;
Cat* cat2 = new Cat();
return 0;
}
Usially I don't care about memory, but I want to understand clearly, in what memory do cat1's and... | Let me annotate and answer in-place.
class Cat()
{
public:
Cat()
{
a = 0; // ok: sets the variable a, wherever it lives
(*b) = 0; // not ok: stores an integer 0 to wherever b points
// since b was never initialized to anything, it can write
// anywh... |
5,126,691 | 5,126,706 | Determining array number from string name | For example I have such array:
name[0] = "Griffin";
name[1] = "David";
name[2] = "John";
name[3] = "Abigail";
Then I have in file names ordered in this sequence
John
David
Abigail
Griffin
How I can determine which array number contains name John, just by reading it's name and without running loops for each entry and ... | Instead of using plain array use std::map.
EDIT:
Trivial example
map <string, int> name;
std::string arr[] = {"Griffin", "David", "John", "Abigail"};
for(int i=0;i < 3;++i)
{
name[arr[i]] = i;
}
std::cout <<name["John"]; //prints 2
|
5,126,766 | 5,126,830 | Code generated with eclipse cdt much faster than in command line | I have the following question. I've done a program in C++ using OpenCV. I used Eclipse CDT as an IDE with g++ 4.4 compiler. When I compile the program in command line the binary is about two times bigger and much slower than that done with eclipse. In both cases I use dynamic linking (at least I think so) and I use no ... | You should look the optimization option that Eclipse is using too compile your program.
For example, the -Os option tells GCC to reduce the size as much as possible.
|
5,127,049 | 5,127,217 | MPI send and receive struct of structs | how can i send and receive this type of structs via MPI?
struct controlPoint{
int hour,minute,second,x,y,z;
};
struct flight{
int flightNum, controlNum;
vector<controlPoint> point;
};
vector<flight> flights;
a sample code will be very helpful
| You'll need to invoke the magic of user-defined datatypes. First, define an MPI_Contiguous datatype for controlPoint: let's call it cp_type. Next, you'll need an MPI_Struct to represent flight, which we'll call flight_type. This is a bit tricky, since you can't pass a vector through MPI (without outside help from e.g. ... |
5,127,072 | 5,127,377 | Obtain POSIX semaphore's name | is there any way to obtain a POSIX named semaphore's name given its ID (sem_t) within C++?
Thanks to all and best regards.
| Unfortunately, no. There is no sem_name (or whatever you'd call it) function in the POSIX semaphore spec. There is also no Linux-specific workaround, since it provides no sem_name either and it does not store the name in the sem_t, which is defined in <bits/semaphore.h> as
typedef union
{
char __size[__SIZEOF_SEM_T];... |
5,127,079 | 7,740,221 | IHTMLEventObj::put_keyCode fails in IE9 RC | I have an IE BHO created over 3 years ago that uses IHTMLEventObj::put_keyCode function. This function has worked as documented in IE6, IE7 and IE8. However, when testing with IE9 RC it no longer works as documented. The function is called the same way and the result is S_OK, but the key does not show up in the input f... | Finally after opening a case and many weeks, a fix was released: The IHTMLEventObj::put_keyCode function does not work in Internet Explorer 9 Standards mode.
Thank you Microsoft!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.