question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,966,835 | 4,967,288 | Is this the proper way of freeing Pointer Memory in c++ | this is a example, I am struck with whether it is a a proper way of freeing the pointer assigned memory
char* functionTest()
{
char *a = new char[10];
return a;
}
int main()
{
char *b;
b=functionTest();
delete[] b;
return 0;
}
This is a very beginner question but still wou... | Technically correct C++ (as of this time with the edit using delete[])
The code would compile and run without errors.
However in production C++ code you will very rarely use new[] and delete[], and will be far more likely to use vector, or for string handling use string.
If you do really want to allocate an array wit... |
4,967,093 | 4,967,391 | Thin vs thick adapter (wrapper) example | I can't find any info on what is the difference between a thin and thick adapter. I would appreciate if someone can provide a description, followed with a simple example (Please note that the example doesn't need to be in C++).
Thanks in advance.
EDIT: my vision of this is something like a class adapter pattern that r... | This is quite simple.
For example, lets say you want to use the stat function in your code, but you want to be able to unit test your code, or even change which function to use at runtime. Then you would add a base class :
struct FunctionApiBase
{
virtual ~FunctionApiBase{}
virtual int stat(const char *path, struct ... |
4,967,154 | 5,101,028 | ZLib.lib(d000062.o) : warning LNK4078: multiple '.text' sections found with different attributes | I downloaded zlib from their website and I have the link warning from the title. I also compiled zlib and still have same warning. Do you know how may I fix this? I don't like warning of any kind in my projects:)
I use Visual Studio 2010.
| Apparently the compiler used to generate the .lib import for the DLL isn't entirely compatible with Visual Studio:
I thought MinGW can be a one-stop shop
that'll do what's needed, and we won't
need anymore the awkward two-tool
combination that we used to use around
zlib-1.2.3. It seems we need another,
even ... |
4,967,158 | 4,967,394 | Opinions on my data storage problem (database/homebrew solution) | I have very simply structured data which is currently stored in a home-brew file format, but I am wondering whether we should migrate to something more modern. The data is simply a table of doubles, indexed by a double column. The things I need to perform are:
Iterating through the table.
Insertion and deletion of arb... | SQLite meets nearly all of your requirements, and it's not that hard to use. Give it a try!
It's file-based, and the entire database is a single file.
It does not need to read the entire file into memory. Database size might be limited; you should check here if the limits will be a problem in your situation.
The forma... |
4,967,221 | 4,967,237 | Copy constructor not called ! | I don't understand why in this case copy constructor isn't called. Can some one please explain ?
#include <iostream>
class foo
{
int* ptr;
public:
foo()
{
std::cout << "\n Constructor \n" ;
ptr = new int;
*ptr = 10;
}
foo( const foo* &obj ) // Copy Constructor
{
... | Because you're just creating another pointer to the same object, not a new object:
foo* objOne = new foo;
foo* objTwo = objOne;
^
|
+-- these are pointers.
If you want a new object, use something like:
foo objTwo = objOne;
and fix your copy constructor:
foo (const foo &obj) ...
The following snippet shows o... |
4,967,250 | 4,967,327 | Objection to exceptions | One of my friends raised this problem to me. I was stuck because I am not an adept at using exceptions. Keep in mind that we both work in an working environment where we use C++ but do error handling in C tradition. His problem was something like this:
Function A calls B which in turn calls C. An exception is thrown fr... | There is a technique developed by Andrei Alexandrescu and Joshua Lehrer called Scope Guard which provides a technique for providing a "scope-exit" code as soon as you allocate an object, and opening the scope for it at that point.
The D programming language actually has it as standard.
boost libraries has an enhancemen... |
4,967,401 | 4,967,469 | Specialize hashmap template | I'm using the hash_map in C++ and want to supply a simplified type name for it:
The key type and hasher function are always the same.
stdext::hash_map<std::string, [MAPPED TYPE], CStringHasher>
However, I don't really want to write all this every time I declare a hash map which maps strings to type X.
Can I write a t... | As others said, template aliases is the way to go if you can use C++0x:
template < typename MappedType >
using StringHashMap = stdext::hash_map< std::string, MappedType, CStringHasher >;
StringHashMap< int > mapA;
StringHashMap< bool > mapB;
(As @MSalters noted, if you have C++0x available, you should probably use st... |
4,967,468 | 4,967,486 | Why does this C++ program cause a memory leak? | Consider the following piece of code:
char* str1 = new char [30];
char* str2 = new char [40];
strcpy(str1, "Memory leak");
str2 = str1;
delete [] str2;
delete [] str1;
Why does the above program cause a memory leak? How do I avoid this?
| Because you're deleting str1 (the memory it points to) twice and you don't delete the memory allocated under where str2 was first pointing to.
EDIT:
I'm not sure what you're trying to achieve.
char* str1 = new char [30];
// str1 = 0x00c06810; (i.e.)
char* str2 = new char [40];
// str2 = 0x00d12340; (i.e.)
strcpy(str1, ... |
4,967,660 | 4,968,183 | Selecting a row in QTreeView programmatically | I have a QTreeView with QFileSystemModel as model.
The QTreeView has SelectionBehavior set to SelectRows.
In my code I read a dataset to select and then select them via:
idx = treeview->model()->index(search);
selection->select(idx, QItemSelectionModel::Select);
This selects a cell, not the row . .
Have added a stu... | You can also select an entire row using an QItemSelection:
selection->select (
QItemSelection (
treeview->model ()->index (search, 0),
treeview->model ()->index (search, treeview->model ()->columnCount () - 1)),
QItemSelectionModel::Select);
Also if you also want row selection for user clicks y... |
4,967,800 | 4,967,834 | About selecting a MFC CListCtrl item | What I'm trying to do is select an item in a CListCtrl and make the selected item visible (scroll down). What is the best way to do this?
I have tried myListCtrl.SetItemState(idx, LVIS_SELECTED, LVIS_SELECTED) to select the item but I have to manually scroll down the ListCtrl to make it visible. There exists the functi... | You can try with EnsureVisible()
http://msdn.microsoft.com/en-us/library/tbtcxzsf%28VS.80%29.aspx
|
4,967,883 | 4,967,952 | How do I randomly generate an array of doubles with a mean of 0 and standard deviation of 1? | for my homework assignment I'm to generate a set of numbers to a fixed point that allows for the mean to be 0 and the standard deviation to be 1. I've been mainly dealing with an array of doubles to attempt this but I'm not sure how to accomplish this.
For generating the values, I've tried using Box Muller method but I... | A good general way to go about this is to generate numbers that follow a standard normal distribution (defined as a normal distribution with µ=0 and σ=1). Take a look at the Wikipedia article for the normal distribution, specifically the section that says "Generating values from normal distribution".
|
4,967,968 | 4,967,982 | Converting C++ solution to a class library | this might be a simple question, but as I have zero experience in C++ and my boss has given me a C++ solution work with I need to ask this question.
I have a C++ solution that needs to be turned into a .NET class library which can then be used in another .NET solution done in C#.
Is this even possible???
Cheers
| You have to wrap all C++ classes that should be visible in .NET in C++/CLI classes.
Read this
There are also some automated tools to do this, but I never used these (I don't really trust them). Depends on how many C++ classes do you have, and how complex they are. Writing the wrappers is mostly straight-forward once yo... |
4,968,033 | 4,968,060 | Why does casting an int to a bool give a warning? | Shouldn't it be ok to use static_cast to convert int to bool as it converts reverse of implicit conversion but i still get a warning?
Example:
MSVC++ 8
bool bit = static_cast<bool>(100);
| Just because the conversion a => b is implicit doesn’t say anything about the viability of the reverse, b => a.
In your case, you shouldn’t cast at all. Just do the obvious thing: compare:
bool result = int_value != 0;
This is the only logically correct way of converting an int to bool and it makes the code much more ... |
4,968,105 | 4,968,175 | C++ inline assembly: how to deal with references? | How to deal with references in function from inline assembler? I'm trying this
void foo(int& x)
{
__asm mov x, 10
}
int main()
{
int x = 0;
foo(x);
std::cout << x << std::endl;
}
but x is still 0 after function execution, however this one works fine
int x = 0;
__asm mov x, 10
std::cout << x << std::en... | A reference is a pointer with value semantics - in assembly language these semantics are irrelevant, so you are left with a pointer:
void foo(int& x)
{
__asm {
mov eax, x
mov DWORD PTR [eax], 10
}
}
(Of course, YMMV depending on the compiler, version, optimisations, etc. all the usual stuff wh... |
4,968,440 | 4,968,638 | Accuracy in addition | I am working on a tool in C to count some incoming/outgoing bits, I want to preserve the bits and not lose them by changing to bytes.
In the end I want to display xxxxx bits downloaded/uploaded. I am putting the maximum on 10GB=85899345920bits which needs roughly 35 bits to be represented. I am using a 32 bit OS.
I tri... | You could take a bit of a hybrid approach: store the number of bytes into one variable and the number of bits that are extra into another variable. Similar to how POSIX systems return the time since the epoch in both seconds and microseconds:
struct timeval {
time_t tv_sec; /* seconds */
... |
4,968,545 | 4,968,631 | Problems with creating a mouse hook using the Windows API | I am trying to create a mouse hook using the Windows API. Currently, I have the following code, but I am struggling to make it work. Perhaps some sample code would help me to understand the concepts better.
LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
HWND hWindow , hEntryWnd;
HRESULT h... | Are you clicking the mouse button more than 30 times? There will be an WM_LBUTTONDOWN message sent each the the mouse button is clicked, even if it is part of a double-click. That's a consequence of how Windows recognizes a double-click in the absence of a way to go back in time.
This sample looks trustworthy, and was... |
4,968,691 | 4,968,790 | C++: Create object of certain type mapped to an enum | Considering the following code example:
class Base;
class A; class B; class C; //A, B and C are inherited from Base
enum TypeID
{
TYPE_A = 0, TYPE_B, TYPE_C, TYPE_MAX;
}
class SomeContainer
{
private Base* objects[ TYPE_MAX ];
public void Add( TypeID what )
{
if( objects[ what ] ) return;
... | Something along these lines should work:
class A; class B; class C;
template<class T>
struct type_index;
template<>
struct type_index<A> { static const size_t index = 0; };
template<>
struct type_index<B> { static const size_t index = 1; };
template<>
struct type_index<C> { static const size_t index = 2; };
templat... |
4,968,854 | 4,968,880 | Is the behaviour of i = i++ really undefined? |
Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
According to c++ standard,
i = 3;
i = i++;
will result in undefined behavior.
We use the term "undefined behavior" if it can lead to more then one result. But here, the final value of i will be 4 no matter what the or... | The phrase, "…the final value of i will be 4 no matter what the order of evaluation…" is incorrect. The compiler could emit the equivalent of this:
i = 3;
int tmp = i;
++i;
i = tmp;
or this:
i = 3;
++i;
i = i - 1;
or this:
i = 3;
i = i;
++i;
As to the definitions of terms, if the answer was guaranteed to be 4, that ... |
4,969,006 | 4,970,220 | Working with Excel 2007 from win32 application | Can you tell me Where I can see a examples (sources of simple application on c++ (for Visual Studio)) a working with excel 2007 and 2003 from win32 application. Especially with Chart object. Thanks!
| One you created COM object of Excel.Application, you can call the same methods this object have in VBScript.
Use some wizard of your IDE to make a wrapper for this ActiveX or use this awkward method:
http://support.microsoft.com/kb/216686
|
4,969,233 | 4,969,304 | How to check if enum value is valid? | I am reading an enum value from a binary file and would like to check if the value is really part of the enum values. How can I do it?
#include <iostream>
enum Abc
{
A = 4,
B = 8,
C = 12
};
int main()
{
int v1 = 4;
Abc v2 = static_cast< Abc >( v1 );
switch ( v2 )
{
case A:
... | enum value is valid in C++ if it falls in range [A, B], which is defined by the standard rule below. So in case of enum X { A = 1, B = 3 }, the value of 2 is considered a valid enum value.
Consider 7.2/6 of standard:
For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the en... |
4,969,619 | 4,974,720 | Prevent my window from flashing when inactiv under short period | I'm creating av On screen keyboard. To send keys I do following (pseudocode):
SetMyWindowTopMost(true)
SetReceiverWindowActive()
Sleep(100)
SendInput(keys)
SetMyWindowActive()
SetMyWindowTopMost(false)
I give focus to another application for a short time (~100 ms) and then regains focus. But I do not want it to appear... | You would be handling WM_NCACTIVATE message for the period of the possible flash. Either prevent the message to reach DefWindowProc, or modify wParam to be 'true' as in this answer.
|
4,969,850 | 4,969,926 | GCC error when compiling MS VC++ code with templates | we're taking some code written for Visual Studio 2008 and try to compile it with gcc. We experienced an error in the following code (simplified to what's necessary):
template<int R, int C, typename T>
struct Vector
{
template <typename TRes>
TRes magnitude() const
{
return 0;
}
};
struct A
{
typedef Vector<3,1... | The problem is that since the C++ compiler doesn’t know the actual type of T (let alone T::NodeVector it doesn’t know that magnitude is supposed to be a template. You need to specify that explicitly:
x.template magnitude<double>();
Otherwise C++ will parse the tokens as x, operator., magnitude, operator<, double, oper... |
4,970,373 | 4,970,403 | Command Line windows compiler (cl.exe) target | In the .NET compiler (csc.exe) I can use the option /target:exe to compile into an exe that will keep the console open so that I can see some stderr or `stdout`` output. However I cannot achieve this same functionality using the C/C++ compiler (cl.exe).
My program uses WinMain which means it's an entire UI application.... | the flag you need to create a console application is /subsystem:console, check out the MSDN documentation about it. and it is actually a flag for the linker stage:
link /out:foo.exe /subsystem:console a.obj b.obj
you can however tell the compiler to use certain flags when invoking the linker:
cl /flags /link /subsyste... |
4,970,580 | 4,970,926 | processing an image using CUDA implementation, python (pycuda) or C++? | I am in a project to process an image using CUDA. The project is simply an addition or subtraction of the image.
May I ask your professional opinion, which is best and what would be the advantages and disadvantages of those two?
I appreciate everyone's opinions and/or suggestions since this project is very important to... | General answer: It doesn't matter. Use the language you're more comfortable with.
Keep in mind, however, that pycuda is only a wrapper around the CUDA C interface, so it may not always be up-to-date, also it adds another potential source of bugs, …
Python is great at rapid prototyping, so I'd personally go for Python... |
4,970,865 | 4,972,668 | Boost regex_replace exception: "...This exception is thrown to prevent "eternal" matches..." being thrown on occasion | I am using Boost.Regex(boost-1.42) to remove the first line of a multi-line string(a fairly large string containing multiple lines ending in '\n').
i.e. using regex_replace to do something akin to s/(.*?)\n//
string
foo::erase_first_line(const std::string & input) const
{
static const regex line_expression("(... | Try putting a "beginning of string" marker ("\A" in the default Perl-compatible mode) at the beginning of the regex, to make it more explicit that you want it to match just the first line.
Without explicitly matching the beginning to the string, it looks like boost is applying its "leftmost longest" rule and that's wha... |
4,970,891 | 4,971,421 | Why addresses of two different objects should be different? | I've been reading about this stuff that size of an object should be at least 1 byte (C++: What is the size of an object of an empty class?) and what's wrong about having two empty objects the same address ? After all, we can have two pointers to the same object.
The googling tells me there is something about object ide... | Having two objects at the same address would mean that there would be no way to distinguish between these two objects when referencing them with pointers. For example, in the following code:
EmptyClass o1;
EmptyClass o2;
EmptyClass * po = &o;
po->foo();
Should the foo method be called on o1 or o2?
It could be argued ... |
4,970,922 | 4,972,906 | Full setup of Transform Feedback(openGL) | GLSL 1.50, openGL 3.3.
I've been lately trying to get my tranform feedback working but without success. I still receive error after glBeginTranformFeedback() and as I haven't found any full working code I have stacked up my knowledge with some code that I found and documentation, it should be working well by now but I ... | Take a look at OpenGL Samples Pack. You might be interested in ogl-330-transform-feedback.cpp and ogl-400-transform-feedback-object.cpp. You might even check January 2011 OpenGL drivers status whether latest drivers have any issues with the provided examples.
Good luck.
|
4,970,959 | 4,973,582 | How can I use decltype to get the type of a reference? | I'm working on some code using decltype in CodeGear RAD Studio. I've tried the naive solution, which looks not unlike this:
int main(int, char**) {
int i;
int &ir = i;
decltype((ir)) ir_clone = ir;
}
Of course, this fails to compile: Internal Compiler Error. I rather suspect that there is nothing particula... | Try making a different, more complex expression that results in the same type that you want, such as:
decltype((void(), ir))
I couldn't tell you why it fixes it, but sometimes a different expression will do the trick.
|
4,971,033 | 4,971,331 | Best compression library/format for compressing on the fly and binary search? | I'm looking for a compression library/format with the following abilities:
Can compress my data as I write it.
Will let me efficiently binary search through the file.
Will let me efficiently traverse the file in reverse.
Context: I'm writing a C++ app that listens for incoming data, normalizes it, and then needs to p... | You can just compress a few chunks at a time so that you can decompress them separately, then keep an (uncompressed but small) index to the beginning of each block of chunks in the compressed data. That will allow almost random access to the chunks and still keep them in order by timestamp. The limit case to this is ... |
4,971,286 | 4,971,323 | Java's final vs. C++'s const | The Java for C++ programmers tutorial says that (highlight is my own):
The keyword final is roughly
equivalent to const in C++
What does "roughly" mean in this context? Aren't they exactly the same?
What are the differences, if any?
| In C++ marking a member function const means it may be called on const instances. Java does not have an equivalent to this. E.g.:
class Foo {
public:
void bar();
void foo() const;
};
void test(const Foo& i) {
i.foo(); //fine
i.bar(); //error
}
Values can be assigned, once, later in Java only e.g.:
public... |
4,971,436 | 4,971,499 | What does "static enum" mean in C++? | I recently came across this:
static enum Response{
NO_ERROR=0,
MISSING_DESCRIPTOR,
...
};
It compiles and works under Microsoft VS2005. However, I'm not sure what the 'static' modifier is supposed to do. Is it any different from the following?
enum Response {
NO_ERROR=0,
MISSING_DESCRIPTOR,
...... | That exact code, with just the ellipsis removed, is not valid C++. You can't use the static storage class specifier in an enum declaration; it doesn't make any sense there (only objects, functions, and anonymous unions can be declared static).
You can, however, declare an enum and a variable all in one declaration:
st... |
4,971,479 | 5,049,047 | IXSomething vs ISomething | I stumbled upon a documentation where COM objects have two kinds of interfaces, one starting with I, second with IX. Documentation says that IX is derived from IUnknown, and I is derived from IDispatch.
Is it better to use IX interfaces if I use C++? As far as I understand the I interfaces are designed for scripting la... | The X belongs to the next word. Feed vs XFeed. "Extended", version 2 of the API.
|
4,971,483 | 4,979,051 | How to compile wxsqlite3 and sqlite to get encryption support | I'm working on a c++ project based on wxWidgets. Using wxSqlite3 for accessing sqlite database, and it is working fine. But I wanted to add some encryption for database, here I have problems with accessing encrypted db via wxSqlite3. As far as I know, sqlite doesn't support encryption by default, but wxSqlite3 somehow ... | The encryption extension coming with wxSQLite3 is open source and offers AES-128 or AES-256 encryption (to be chosen at compile time). Guidance how to compile SQLite with encryption support can be found for example here.
|
4,971,926 | 8,765,552 | Launch Failed. Binary not found. CDT on Eclipse Helios | I'm using Eclipse Helios on Ubuntu 10.04, and I'm trying to install CDT plugin on it. I download it from here here.
And then I go to Install New Software and select the zip file (I don't extract it, just select the zip file). And its ok, it installs, everything works fine, it shows optional features, blah blah blah.
A... | You must build an executable file before you can run it. So if you don't “BUILD” your file, then it will not be able to link and load that object file, and hence it does not have the required binary numbers to execute.
So basically right click on the Project -> Build Project -> Run As Local C/C++ Application should do ... |
4,971,928 | 4,972,033 | Embedding Python into C++ application | Context:
An ongoing problem we have been facing is unit testing our market data applications. These applications sit and observe data being retrieved from feeds and does something. Some critical events which are hard to trigger rarely occur and it is are difficult for the Testers to verify our applications perform co... | I do something similar to this in one of my projects by using SWIG to generate python bindings for the relevant parts of the C++ code. Then I embed the interpreter as others have suggested. Having done that I can execute python code at will (e.g. PyRun_SimpleString), which can access C++ code. Normally I end up using s... |
4,972,266 | 4,974,390 | Calling a multithreaded (openmp) c++ routine from a Fortran routine | I have a c++ routine standalone_c.cpp and a wrapper for this in fortran standalone_f.f90 which wraps standalone_c.cpp. standalone_c.cpp is multithreaded using a openmp pragma. I am able to compile both standalone_c.cpp and the wrapper standalone_f.f90. However when I try to link these two, I get errors like undefined r... | The -openmp flag on ifort does more than just turn on OpenMP directive processing. It also links in the proper libraries. Assuming that you have handled the underscore in the subroutine naming problem already, then if you add -openmp to the ifort link step, that will take care of the OpenMP libraries and adding -lstd... |
4,972,286 | 4,972,606 | Compile error with pointer to template function in Visual Studio 2008 | I'm trying to create a template class that stores a function pointer to a template function, but ran into a compile error in Visual Studio 2008. I created a simplified test case for it(see below) which still fails to compile in VS2008, but appeared to compile successfully on the online Comeau and online GCC compilers ... | It looks to me like the "const T& arg" in test_class and create_class are your problem. Changing those to a simple "T arg" seems to smooth things out.
|
4,972,465 | 4,973,112 | Get data from the web server and sent them to the client c++ | I am trying to get some data from the webserver as a proxy,and then sent the data to the client.
Webserver -> Me -> Client
This is my main code:
int main()
{
Initialize();
ServerSocket s;
s.Bind();
s.Listen();
while(true)
{
TCPSocket* sock = s.Accept();
ClientSocket client;
... | Your code is working just fine. Its just that modern day webservers won't allow you to connect without properly authenticating yourself, using user-agen, headers etc. Try the following commands on your shell.
telnet yourserver.com 80
<some messages from server>
GET /index.html HTTP/1.0
If the response is same as what... |
4,972,470 | 4,972,489 | what is the time complexity of std::next_permutation() function in c++? | I wanted to know the time complexity of the next_permutation function. Can I view its code too ?
| See http://www.sgi.com/tech/stl/next_permutation.html:
Linear. At most (last - first) / 2
swaps.
To see the source code, just look in STL header files for your system. On a Unix-like system, you probably need to look somewhere like /usr/include/c++/4.1.2/bits/stl_algo.h.
|
4,972,498 | 4,972,826 | Widechar to Bytes using bits pattern? | If the number of bytes in UTF-8 encoded wide char is known, would it be possible get bytes using the following method?
For example:
Wide character ¿ code 191 to bytes gives -62 and -65
I've tried to fit the 8 bits in 191 into the slots but didn't get the same result
110[0][0][0][1][0] 10[1][1][1][1][1][1]
127 ... | First, don't convert to signed bytes. That just confuses matters. So code point 191 yields the byte sequence 194 191
Decimal: 194 191
Binary: 110[0][0][0][1][0] 10[1][1][1][1][1][1]
To generate these bytes, you start from the right edge. You get six bits from the 191 and two more from the 194, wi... |
4,972,544 | 4,973,001 | How do you open a file using Symbian's RFile? | I have just started developing for Symbian. I am currently using Nokia Qt. I am trying to launch another application based on mime type. I currently am following this example. I'd like to attempt to open a .txt file.
I am finding it hard to understand how to create a RFile and what the TDesC16 class actually is / doe... | TDesC16 is a Symbian descriptor, which is basically a string. Here is a good manual: http://descriptors.blogspot.com/
As for your problem. In the example it looks like aFileName is meant to be a descriptor.
So to open test.txt do something like this:
TThreadId threadId;
User::LeaveIfError(session.StartDocument(_L("c:\... |
4,972,651 | 4,972,700 | Get date/time of last reboot programmatically | I would like to find the time of the last reboot programmatically in Linux. I am using C and C++ in my module.
Is there an API?
| There's no direct api, but you can read /proc/uptime "file" to learn how many seconds the system have been running, subtract that from the current time - and assume that's when the machine was rebooted.
/proc/uptime
This file contains two numbers: the uptime of the system
(seconds), and the amount of... |
4,972,795 | 4,972,832 | How do I typecast with type_info? | I've stored a pointer to a type_info object.
int MyVariable = 123;
const std::type_info* Datatype = &typeid(MyVariable);
How might I use this to typecast another variable to that type? I tried this, but it doesn't work:
std::cout << ((*Datatype)3.14) << std::endl;
Using the function form of typecasting doesn't work,... | I don't think such casting can be done. Suppose you could do "dynamic" casting like this at runtime (not to mean dynamic_cast). Then if you used the result of the cast to call a function the compiler could no longer do type checking on the parameters and you could invoke a function call that doesn't actually exist.
The... |
4,972,810 | 4,973,076 | Problem writing binary data with ofstream | Hey all, I'm writing an application which records microphone input to a WAV file. Previously, I had written this to fill a buffer of a specified size and that worked fine. Now, I'd like to be able to record to an arbitrary length. Here's what I'm trying to do:
Set up 32 small audio buffers (circular buffering)
Start... | I am just wondering, how
void CaptureApp::writeData()
{
mPcmBufferPosition *= sizeof(int16_t); // mPcmBufferPosition = 0, so 0*2 = 0;
// (...)
mPcmBufferPosition = 0;
}
works (btw. sizeof int16_t is always 2). Are you setting mPcmBufferPosition somewhere else?
void CaptureApp::writeData()
{
// Update h... |
4,972,815 | 4,972,829 | C++ (Visual Studio), Can't write the number '10' to file, all other numbers working? | I have a bit of a weird problem here!
I am trying to write the color table for a 8 bit windows 3.x bitmap file. I just want the file to be greyscale, so i am trying to write bbb0, ggg0, rrr0 256 times where r=g=b=1..256
//write greyscale color table
for (int i = 255; i >= 0; i--) {
writeS = (unsigned short)i;
... | The "number 10" in ASCII is the line feed character, \n. In C++, this is the newline character.
You have apparently opened the file as a text stream. Because newlines are represented differently on different platforms, text streams perform newline translation: when reading they translate the platform-specific newlin... |
4,972,897 | 6,284,366 | PowerBuilder call to C# code crashes on some computers? | I seem to be having an issue when it comes to calling C# code from PowerBuilder, but it only affects some computers.
The program itself is a simple program that allows you to send an E-mail. The application has been written in PowerBuilder 11.2, while the SMTP part has been written in C#/C++ which is created in a Mail.... | Ended up finding out what the problem was. The problem was associated with the building of the .dll through DEBUG mode.
If a .dll is in DEBUG mode, it uses a special version of the .NET Framework that is only available from VisualStudio 20xx.
Simply changing it to RELEASE build allowed this to function on all computers... |
4,973,077 | 4,973,538 | The amortized complexity of std::next_permutation? | I just read this other question about the complexity of next_permutation and while I'm satisfied with the response (O(n)), it seems like the algorithm might have a nice amortized analysis that shows a lower complexity. Does anyone know of such an analysis?
| So looks like I'm going to be answering my own question in the affirmative - yes, next_permutation runs in O(1) amortized time.
Before I go into a formal proof of this, here's a quick refresher on how the algorithm works. First, it scans backwards from the end of the range toward the beginning, identifying the longest ... |
4,973,221 | 4,973,240 | Problem allocating derived class array with new | I have a simple program
$ cat a.cpp
#include <iostream>
class MyClass {
public:
virtual void check() {
std::cout << "Inside MyClass\n";
}
};
class MyClass2: public MyClass {
public:
int* a;
virtual void check() {
std::cout << "Inside MyClass2\n";
... | w = new MyClass2[2];
This creates an array of two MyClass2 objects. It is of type MyClass2[2]. The new expression returns a pointer to the initial element of this array and you assign that pointer to w.
w[1].check();
This treats w as a pointer to an array of MyClass objects, not as an array of MyClass2 objects.
... |
4,973,239 | 4,974,120 | what is __in and WSAAPI? | I saw in the definition of a socket in msdn the following:
SOCKET WSAAPI socket(
__in int af,
__in int type,
__in int protocol
);
What is the prefix "__in" mean?
and what is WSAAPI ?
| __in (and friends) specify the intended use of each parameter, so that calls to that function may be mechanically checked.
See http://msdn.microsoft.com/en-us/library/aa383701(v=vs.85).aspx on how to activate the checking.
http://msdn.microsoft.com/en-us/library/ms235402.aspx describes the modern alternative.
WSAAPI ex... |
4,973,418 | 4,973,459 | Is there another workaround for template base class inheritance? | This code produces an error in the GNU compiler:
class A
{
public:
int X;
};
template<class T>
class Foo : public T
{
public:
void doStuff();
};
template<class T>
void Foo<T>::doStuff()
{
X++;
}
There is already an answer for why this is an error. I would like to know if there is another way of working a... | using T::X should work. If it gives error, there is some other problem with your code, or it must be compiler bug. See yourself : http://www.ideone.com/MI9fM
You may use this pointer, as
template<class T>
void Foo<T>::doStuff()
{
this->X++;
}
This gives compiler a hint where to look for the symbol X.
Demo:... |
4,973,473 | 4,979,181 | Boost Serialization multiple objects | I am serializing a class with boost using binary. I'm using ios::append in order to keep appending multiple objects to this file. How do I go about retrieving all of the objects that are stored?
Here is my test class which tries a multiple serialize and retrieve them. I've comment the failure point where I don't get... | Decided to add another answer to avoid complete mess.
Your problem is that you serialize to separate instances of boost::archive::binary_oarchive. Boost Archive stores some internal info at the beginning of the file (I won't call it a header because Boost Serialization has separate header to store version number), and ... |
4,973,551 | 4,973,704 | Problems with SDL_SetColorKey | I'm trying to create a transparent sprite with SDL. I'm using SDL_SetColorKey on a bitmap with magenta (0xff00ff) background (it's 100% magenta, I checked it with the GIMP :)) The call to SDL_SetColorKey looks like this:
SDL_SetColorKey( bitmap, SDL_SRCCOLORKEY, SDL_MapRGB(bitmap->format, 255, 0, 255) );
The call to SD... | The problem is with your image, i used one generated by me and it works out of the box with your code.
Your image is in 32 bits and it seems that SDL_SetColorKey doesn't like it, convert it to 24 bits and it should work.
You can convert it with Gimp when you save it to BMP from the advanced settings.
Try with this one ... |
4,973,625 | 4,988,548 | Why do INSERT and DELETE screw up QTableView (Qt, C++, sqlite)? | After setting an INSERT or DELETE query on QSqlQueryModel, my QTableView becomes screwed up. For example I hid the ID column by calling view->hideColumn(ID); but after an INSERT or DELETE the ID column becomes visible.
How can I automatically reset my view to the previous settings in these cases?
| I guess the problem is in QSqlQueryModel::setQuery you're eventually calling every time content gets reloaded and rows inserts\deletes. Looking at the setQuery implementation I would suggest: depending on the query your model can be reset including columns settings change which should trigger view columns update.
As Q... |
4,973,776 | 4,974,002 | C++ - Behavior of function template specialization with rvalue reference | I'm trying to implement a conditional pointer dereferencing function. The basic idea is as follows:
return is_pointer(arg) ? *arg : arg
In order to limit the number of necessary specialization, I'm attempting to use rvalue references for the case where arg is not a pointer. Here is my current implementation (the std::... | As far as I understand
template <T>
void foo(T&&)
means that if T is a lvalue, it will be deduced as a reference (T = int*& in your case) and after reference collapsing of int*&&& yields a regular lvalue reference int*&. If it wasn't like that, this syntax would capture anything as a rvalue reference. Whereas the poin... |
4,973,905 | 4,973,939 | Taking input from stdin after freopen() | Hi I want to how can we take input from stdin again after I invoke:
freopen("Smefile.txt","r",stdin);
Precisely I want my first in first of my program should take input from a designated file the next part would take from the stdin.
Like:
int a,b;
freopen("Smefile.txt","r",stdin);
scanf("%d",&a);
{
//some bloc... | You can't. Use
FILE *input = fopen("Smefile.txt","r");
// read stuff from file
fclose(input);
input = stdin;
instead.
This won't help when you're mixing C++ and C-style I/O on the same stream, which I wouldn't recommend anyway.
(If you happen to be on Linux, you can reopen /dev/stdin instead. On Linux/Unix, you can ... |
4,973,921 | 4,974,112 | making valgrind able to read user input when c++ needs it | I am trying to run my c++ program with valgrind, however I have some points in the program which require user input from stdin, but when i run with valgrind, it wont let the user input anything for the program, is there a way around this?
Been searching all around but have not found the answer.
| I haven't tried it, but I found this in the man pages:
--input-fd=<number> [default: 0, stdin]
Specify the file descriptor to use for reading input from the
user. This is used whenever valgrind needs to prompt the user
for a decision.
What happens if you specify a differ... |
4,973,974 | 4,974,024 | Is it okay for an object to tell its owner to delete it | I have a scenario that is somewhat like this:
class Owner {
public:
enum Type {TypeB, TypeC};
void swap(Type type);
private:
A* m_a;
};
class A {
};
class B : public A {
void foo();
Owner* m_owner;
};
class C : public A {
void bar();
Owner* m_owner;
};
void Owner::swap(Type type) {
if (type == TypeC... | If you've defined A's destructor as virtual then that is perfectly okay.
By the way, your code needs small correction:
else if (type == TypeB) {
delete m_a; //not m_b, as Owner doesn't have any member named `m_b`.
m_a = new B();
}
But I'm wondering which object gets deleted here, the one which calls swap f... |
4,974,563 | 4,974,644 | How to determine when files are done copying for further processing? | Alright so to start this is strictly for Windows and I'd prefer to use C++ over .NET but I'm not opposed to boost::filesystem although if it can be avoided in favor of straight Windows API I'd prefer that.
Now the scenario is an application on another machine I can't change is going to create files in a particular dire... | This is a fairly common problem and one that doesn't have an easy answer. Acquiring locks is one of the best options when you cannot change the thing at the remote end. Another I have seen is to watch the file at intervals until the size doesn't change for an interval or two.
Other strategies include writing a no-byt... |
4,974,617 | 4,974,655 | What is more efficient stack memory or heap? |
Possible Duplicate:
C++ Which is faster: Stack allocation or Heap allocation
What is more efficient from memory allocation perspective - stack memory or heap memory? What it depends on?
Obviously there is an overhead of dynamic allocation versus allocation on the stack. Using heap involves finding a location where t... | Stack is usually more efficient speed-wise, and simple to implement!
I tend to agree with Michael from Joel on Software site, who says,
It is more efficient to use the stack
when it is possible.
When you allocate from the heap, the
heap manager has to go through what is
sometimes a relatively complex
procedure... |
4,974,709 | 5,721,197 | PCA + SVM using C++ Syntax in OpenCV 2.2 | I'm having problems getting PCA and Eigenfaces working using the latest C++ syntax with the Mat and PCA classes. The older C syntax took an array of IplImage* as a parameter to perform its processing and the current API only takes a Mat that is formatted by Column or Row. I took the Row approach using the reshape funct... | What etarion said is correct.
To copy a column or row you always have to write:
Mat B = mat.col(i);
A.copyTo(B);
The following program shows how to perform a PCA in OpenCV. It'll show the mean image and the first three Eigenfaces. The images I used in there are available from http://www.cl.cam.ac.uk/research/dtg/atta... |
4,974,766 | 4,976,898 | How can I include a DropDownList in a menu bar using the Windows API? | Assuming programming in C++ for the Win32 API, I would know if it is possible to include a DropDownList (COMBOBOX window with CBS_DROPDOWNLIST style) in a menu bar.
Any light in that matter or where start to learn on the topic would be appreciated.
| Owner drawing is your only option for customizing the built-in API menus. Not only is that a giant pain in the rear, it still won't produce the effect that you want. You'd have to draw the combo box by hand and write code to respond to all the mouse events, instead of just dropping in a standard combo box control.
My s... |
4,974,805 | 4,974,821 | C++ subclass parameterized class, and use the subclass as a specialization | I want something like this:
class TestParent<class T>
{
T* some();
}
class TestChild : public TestParent<TestChild>
{};
Is this possible?
Thanks.
| This is possible but only if you define an implementation of some otherwise you'll be confronted by compilation errors. You may also want to add a protected constructor so that your base class can't be created and used outside of how you define it in your header scope.
template<typename T>
class TestParent{
public... |
4,974,931 | 4,975,046 | MARIE assembler - how to multiply | I want to write a simple M.A.R.I.E. program to evaluate the expression A x B + C x D.
Now, there's not alot of info on Marie assembly language.
I am not sure if there is a multiply? If not, would I have to loop or something to get it to multiply?
I know for certain operators like <, > you would subtract.
This is what I... | Do I suppose you refer to this?
http://www.cse.yorku.ca/~jeff/notes/compiler/Marie/
You can access to a list of opcodes in the editor (File>>Edit), Help>>Help.
There is no mult opcode, so you'll have to create a loop and use skipcond in order to test the condition.
|
4,974,992 | 4,975,052 | Can this be done with multiple inheritance? | Here is what I would like to do.
Say I have Class Widget.
I then create Button from Widget.
I then create ModifiedWidget which re-implements certain functions of Widget.
I then want Button to use ModifiedWidget rather than plain Widget. Is this possible to do some how?
Thanks
class Button : public Widget;
class SuperB... | The easiest way is to use encapsulation, not inheritance.
class Button
{
Button(Widget * w) { mywidget = w; }
Widget * mywidget;
};
Another way is to let Button be a template class.
template<class Parent>
class Button : Parent
{
};
Button<Widget> mybutton1;
Button<ModifiedWidget> mybutton2;
|
4,975,001 | 4,975,311 | Opening QDialog in a non-blocking manner | I have a QDialog which I open like this:
void MyModule::openDialog() {
this->dialog->open();
printf("Hello World");
}
The dialog opens just fine, but unfortunately "Hello World" isn't printed when calling openDialog() - even after closing the dialog. However, when I open another completely unrelated file dialo... | It depends on the OS but generally printf() doesn't play nicely with GUIs.
On windows for instance nothing would appear, on unix you could do fprintf(stdout, ) and then fflush(stdout) or fprintf(stderr, ) which isn't buffered
If this is just a debug function, take a look at qDebug() - it's what it's there for.
|
4,975,037 | 4,975,112 | Why are the bits of a std::bitset in reverse order? | Why does bitset store the bits in reverse order? After strugging many times I have finally written this binary_to_dec. Could it simplified?
int binary_to_dec(std::string bin)
{
std::bitset<8> bit;
int c = bin.size();
for (size_t i = 0; i < bin.size(); i++,c--)
{
bit.set(c-1, (bin[i]-'0' ? true... | Bitset stores its numbers in what you consider to be "reverse" order because we write the digits of a number in decreasing order of significance even though the characters of a string are arranged in increasing index order.
If we wrote our numbers in little-endian order, then you wouldn't have this confusion because th... |
4,975,146 | 4,975,168 | boost c++ library object serialization problem | The error was:
terminate called after throwing an instance of 'boost::archive::archive_exception
what(): input stream error
Aborted
I have these code in my main.c
Object *obj = new Object();
{
std::ifstream ifs("FILEX");
boost::archive::text_iarchive ia(ifs);
ia >> *obj;
}
"FILEX" may or may not exist bef... | My favorite reference page when using ifstream:
http://www.cplusplus.com/reference/iostream/ifstream/
You're trying to open "FILEX" twice -- I assume that's not what you want to do. I'm not familiar with boost::archive, but you can at least check if ifs is usable:
Object *obj = new Object();
{
std::ifstream ifs("F... |
4,975,190 | 5,053,509 | Want to implement a VPN for just one application | I looking for add support to a VPN for my software,
I known PPTP and OpenVPN , the two makes a system-wide binding, installing a TAP driver so all applications route their traffic to then.
How could i implement a VPN support for just my application ? There´s any library, example, hint or way to do it ?
My software is a... | Forwading incoming connections to your application is relatively easy:
stunnel allows you to forward traffic to specific ports through an an SSL tunnel. It requires that you run it on both ends, though.
Most decent SSH clients, such as OpenSSH or PuTTY also support port forwarding, with the added advantage that any re... |
4,975,221 | 4,975,272 | C/C++ map binary data to struct members | Lets say, I have the following text file:
Listing 1:
Endianess=little
AddressModel=32
typedef struct{
int x;
int y;
float f;
double d;
} A;
instance1:0x0000000100000002000048C19A99999999993C40
instance2:0x00100257000000090000000FBA99359976992397
Where instance1 corresponds to an instance of struct A, ... | You cannot use reflection in C or C++ so that's out. That means you will need to write a parser than can read C struct definitions. Not hard at all really.
You can do it yourself if you want: tokenizing and parsing C is not hard. Or you could use tools like lex and yacc. Or you could use a C++ library like Boost Spirit... |
4,975,263 | 4,975,759 | C++ Arbitrary width container | I have a large lookup table that currently needs 12 bits per entry. Is there a standard class that will give me a memory efficient container for storing odd-sized data? I have about a billion items in the table, so I care more about memory efficiency than speed.
I need to be able to get the underlying data and read/wri... | How about this:
#include <stdio.h>
typedef unsigned char byte;
typedef unsigned short word;
typedef unsigned int uint;
typedef unsigned long long int qword;
enum {
bits_per_cell = 12, cellmask = (1<<bits_per_cell)-1,
N_cells = 1000000,
bufsize = (N_cells*bits_per_cell+7)/8,
};
byte* buf;
byte* Alloc( void ) {... |
4,975,324 | 4,975,497 | Real time physics with MPI | I am considering working on a rigid body parallel physics engine, with MPI, as my own project. Have some experience with serial engines. So far, I couldnt find any existing projects of that type, does enyone knows about such things?
I know that MPI is not the best choice for real time physics, lots of time will be los... | If you can fit the job into the available memory then a GPU (either CUDA or OpenCL) may be the way to go.
MPI isn't really made for responsiveness, even with exotic low latency interconnects the message passing is slow. Unless it;'s changed since my day a lot of the code is polling nodes and waiting for a reply which d... |
4,975,340 | 4,975,363 | int to unsigned int conversion | I'm just amazed to know that I can't convert signed to unsigned int by casting!
int i = -62;
unsigned int j = (unsigned int)i;
I thought I already knew this since I started to use casts, but I can't do it!
| You can convert an int to an unsigned int. The conversion is valid and well-defined.
Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)
In this case, since int on... |
4,975,356 | 4,975,885 | Custom STL container wrapper report weird compiler error | I have a C++ library (with over 50 source files) which uses a lot of STL routines with primary containers being list and vector. This has caused a huge code bloat and I would like to reduce the code bloat by creating another library which is essentially a wrapper
over the list and vector.
I basically need a wrapper a... | I think the problem is that the line
currentElement->getPosition();
won't work because currentElement is an iterator over void*s, not labels. Since iterators over some type T act like T*s, this means that your currentElement iterator acts like a label**, and so writing the above code is similar to writing
(*currentEl... |
4,975,394 | 4,975,435 | iterator pattern - error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' | I am trying to iterate and print using the iterator pattern but i get an erorr
here is the error:
error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'std::string' (or there is no acceptable conversion)
1> could be 'std::basic_ostream<_Elem,_Traits> &std::operator <<<char,std::char... | //#include <string>
You aren't including the <string> header. You've commented out the include directive.
In the Visual C++ Standard Library implementation, std::string can be used when you include <iostream>, but the operator<< overload that allows insertion of an std::string into an std::ostream is only included if... |
4,975,504 | 4,986,415 | Zero cost exception handling vs setjmp/longjmp | Assuming that there is a cost associated with setting recovery point, one could optimize a loop like this:
while (doContinue) {
try {
doSomeWork ();
}
catch (...) {}
}
Into something like this:
while (doContinue) {
try {
do {
doSomeWork ();
} while (doContinue);
break;
} c... | Zero-cost approach can be used only if available for the target in use. If available, it is used by the most production-quality C++ compilers. Otherwise compiler will use setjmp/longjmp approach.
Execution speed of setjmp/longjmp is slower.
However, even with setjmp/longjmp approach in use, using exceptions mechanism c... |
4,975,512 | 4,978,686 | TCP server with state information using network library | I'm writing a tcp server for an online turn-based game. I've already written a prototype using php sockets, but would like to move to C++. I've been looking at the popular network libraries (ASIO, ACE, POCO, LibEvent), but currently unclear which one would best suit my needs:
1) Connections are persistent (on the order... | Boost.Asio should meet your requirements. The reactor queue can be serviced by multiple threads. Using asynchronous methods will enable your design of a fixed number of threads servicing all connections.
The tutorials and examples are probably the best place to start if you are unfamiliar with the library.
|
4,975,691 | 4,975,705 | C++: templated inherited recursive classes: impossible triple-threat? | So, say you have a base class which is recursive (e.g. a linked list) and a derived class as well. The derived class should reuse the constructor from the base class, because you don't want to write redundant code. You could try the obvious thing, and it won't work:
class Base {
public:
Base(int size) {
if ... | The problem is that the base class, Base<T, Derived<T> >, is a dependent base class because it depends on the template parameters, but next is not a dependent name because it doesn't depend on the template parameters. The compiler does not look up nondependent names in dependent base classes.
You can fix this problem ... |
4,975,711 | 4,975,884 | Ignore user input outside of what's to be chosen from | I have a program in which the user must make a selection by entering a number 1-5. How would I handle any errors that might arise from them entering in a digit outside of those bounds or even a character?
Edit: Sorry I forgot to mention this would be in C++
| Be careful with this. The following will produce an infinite loop if the user enters a letter:
int main(int argc, char* argv[])
{
int i=0;
do {
std::cout << "Input a number, 1-5: ";
std::cin >> i;
} while (i <1 || i > 5);
return 0;
}
The issue is that std::cin >> i will not remove anything from the in... |
4,975,722 | 4,975,785 | Typedef and ostream operator for a std::vector | I created a class Chromosome that ended up simply being a wrapper for vector with an ostream operator, so I've decided to typedef vector instead. However, I'm having trouble with the templated ostream operator... Is this the best way to go about it? (I've seen a few approaches and have failed to get any to work)
templa... | Unfortunately, there's no clean way to do this because the compiler can't deduce the type of G from the function declaration
template<typename G>
std::ostream& operator<<(std::ostream& os, const typename Chromosome<G>::type& chromosome);
The reason is that if you were to specialize Chromosome for different types, you ... |
4,975,833 | 4,975,867 | Connect TCPIP clashes with QT Connect | I am having a problem with the connect function for TCPIP because QT has a similar function connect.
no matching function for call to MainWindow::connect(SOCKET&, sockaddr*, unsigned int)
Can someone help me with this error?
Thanks.
| If you want to disambiguate between the global function and the one in MainWindow, you can use the scope resolution operator:
::connect(/* ... arguments go here ... */)
The use of :: here tells the compiler to look at the global scope for the function, rather than using the standard name lookup technique that would fi... |
4,976,018 | 5,019,604 | compile-time string hashing | I need to use a string as the ID to obtain some object. At implement this in a run-time, and works well. But this makes the static type checking impossible, for obvious reasons.
I've Googled for the algorithm for calculating the hash-sum of string in the compile-time: C++ compile-time string hashing with Boost.MPL.
It... | Solution with gcc-4.6:
#include <iostream>
template<size_t N, size_t I=0>
struct hash_calc {
static constexpr size_t apply (const char (&s)[N]) {
return (hash_calc<N, I+1>::apply(s) ^ s[I]) * 16777619u;
};
};
template<size_t N>
struct hash_calc<N,N> {
static constexpr size_t apply (const char (&s)[... |
4,976,677 | 4,976,724 | Write CSV file into vectors in C (continued) | Basically I have 14800x8 matrix that has been extracted from matlab as CSV file ("moves.mo"). I need to read this file into 14800 vectors with 8 values each.
Here is a few lines from the file:
1,2,3,4,-1,-3,-2,-4
1,2,3,5,-1,-3,-2,-5
1,2,3,6,-1,-3,-2,-6
1,2,3,7,-1,-3,-2,-7
1,2,3,8,-1,-3,-2,-8
1,2,3,9,-1,-3,-2,-9
I wrot... | There are better ways to read integers in C++. For example:
std::string s;
if (!getline( inputfile, s )) break;
istringstream ss( s );
int recordedMove;
while (ss >> recordedMove)
{
recordmove.push_back(recordedMove);
// consume the commas between integers. note if there are no
// separating commas, you ... |
4,976,703 | 4,977,490 | volatile variable and atomic operations on Visual C++ x86 | Plain load has acquire semantics on x86, plain store has release semantics, however compiler still can reorder instructions. While fences and locked instructions (locked xchg, locked cmpxchg) prevent both hardware and compiler from reordering, plain loads and stores are still necessary to protect with compiler barriers... | Volatile keyword is available in C too. "volatile" is often used in embedded System, especially when value of the variable may change at any time-without any action being taken by the code - three common scenarios include reading from a memory-mapped peripheral register or global variables either modified by an interru... |
4,976,905 | 4,977,053 | wxWidgets and Dev-C++ | I've been using Bloodshed Dev-C++ for C++ programing for a while now. I'd like to get into GUI programing in C++. So I installed wxWidget and tried a simple hello world program, yet I get the following error:
\Dev-Cpp\gui_at0.cpp C:\Dev-Cpp\C wx/wx.h: No such file or directory.
I'm pretty sure this error is due to th... | Uff, long time since I worked with Dev-C++, but basically you need to tell your compiler where to find the wxWidgets library. It should be somewhere around Compiler Options -> Include Directories or the likes. Also see here. If you can't find those options, another way to get it working is to copy the wxWidgets library... |
4,977,021 | 4,982,426 | Assigning pointer to an index in an array of pointers | I have a C++ class where I have a dynamically-allocated array of pointers to structs. I have a member function to "add an item" to this array by assigning an index of the array to the pointer to a dynamically allocated instance of the struct.
I have sort_arr initialized with sort_arr = new node *[this->max_items];.
In ... | As noted, the code does appear to be correct. The problem was unrelated to the referenced code. I had been debugging some memory leaks and was deleting the referenced items, which was in turn causing the problem (quite obviously now that I see that).
I appreciate everyone's help and I'm sorry if I drove anyone crazy tr... |
4,977,050 | 4,977,220 | Spliting std::string and a character array into two halves (efficiently) | How can we split a std::string and a null terminated character array into two halves such that both have same length?
Please suggest an efficient method for the same.You may assume that the length of the original string/array is always an even number.
By efficiently I mean using less number of bytes in both the cases, ... | You've already received a C++ answer, but here's a C answer:
int len = strlen(strA);
char *strB = malloc(len/2+1);
strncpy(strB, strA+len/2, len/2+1);
strA[len/2] = '\0';
Obviously, this uses malloc() to allocate memory for the second string, which you will have to free() at some point.
|
4,977,172 | 4,977,190 | Hiding 'static' class variables | So I recently found some source code which used a particular technique(idiom?) I hadn't seen before; to put it simply; instead of using a static variable for the class in question, it used a local variable inside the classes source file.
myclass.h
class myclass {
//static int myint;
public:
myclass();
~myc... | It doesn't really matter whether you use a static member variable or a global variable or a locally declared static variable; the only important thing is that the object has to have static storage duration. Beyond that, the choice is mostly based on personal preference or coding style guidelines.
Unfortunately, this c... |
4,977,252 | 4,977,525 | Why an unnamed namespace is a "superior" alternative to static? | The section $7.3.1.1/2 from the C++ Standard reads:
The use of the static keyword is
deprecated when declaring objects in a
namespace scope; the unnamed-namespace
provides a superior alternative.
I don't understand why an unnamed namespace is considered a superior alternative? What is the rationale? I've known ... |
As you've mentioned, namespace works for anything, not just for functions and objects.
As Greg has pointed out, static means too many things already.
Namespaces provide a uniform and consistent way of controlling visibility at the global scope. You don't have to use different tools for the same thing.
When using an an... |
4,977,290 | 4,977,321 | static var in member function | bool SomeClass::Function( bool thankYou = true )
{
static bool justAbool = false;
// Do something with justAbool;
...
}
I have searched around but I can't find anything about this except globals vars or member functions itself.
What does the above do, i.e. what happens, does justAbool keep its value after... | static when applied to a local variable gives that variable static storage duration. This means that the justAbool's lifetime lasts to the end of the program rather than to the end of the invocation of the function. It's scope stays the same, it can only be accessed by name in the function, after the declaration appear... |
4,977,330 | 4,977,362 | Static members class vs. normal c-like interface | Hey there.
After reading here about the Service Locator pattern, it got me thinking wether a class with only static members really is the way to go, or if a normal c-like interace wouldn't be more appropriate. I see people throwing around the class keyword all the time when they don't even need it.
Example with static ... | Your proposal with namespaces has a slight weakness in maintainability - if you need to change the interface for some reason, you have to remember to change both the interface (.h) and implementation (.cpp), or a mismatch may not be detected until link time. If you use a class, then the compiler can detect an error suc... |
4,977,554 | 4,977,562 | function defintion in header file in C++ | I have C++ project which consists of multiple (in fact many) .cpp and .h files. While writing header files i have a file as follows
For eg MyHeaderFile.h
#ifndef _MYHEARDERFILE_H
#define _MYHEARDERFILE_H
// Here i have function defintion.
void myFunc() {cout << "my function" << endl; }
#endif
Above file is included ... | Normally, one puts function declarations in header files, and function definitions (i.e. the actual function body/implementation) in source files. Otherwise, you get exactly the issue you're seeing: the header file is #included (i.e. substituted) into multiple source files, so the function ends up being defined multip... |
4,977,600 | 4,977,633 | Error when forward declaring a struct: "has a previous declaration here" | When building my small C++ project, I get the following 2 errors, can't figure out the cause:
error: using typedef-name 'TTF_Font' after 'struct'.
Points to the following line of code: struct TTF_Font; in Foo.h.
error: 'TTF_Font' has a previous declaration here.
Points to the following line of code: typedef struct ... | You are trying to forward declare something as a different type to what it actually is.
You are declaring:
struct TTF_Font;
when the error message indicates that TTF_Font is actually a typedef, not a struct:
typedef struct _TTF_Font TTF_Font;
The stuct is actually called _TTF_Font.
You can declare the same typedef mu... |
4,977,669 | 4,977,692 | Is it right to declare variables using macros in header file in C++? | I encountered a problem when declare some global variables using macros. Here is the case:
the original code:
/* some_config.h */
static const std::string KEYWORDS_A[] = {"AXX", "AYY"};
static const std::vector<std::string> KEYWORDS_A_VEC(KEYWORDS_A, KEYWORDS_A + sizeof(KEYWORDS_A) / sizeof(KEYWORDS_A[0]));
sta... | Your compilation problem is caused because you need a tokenization thing in every place that you intend to tokenize, e.g.:
#define REGISTER_NAME(NAME) blah_##NAME##_blah
(Note use of ## on both sides of NAME.)
As to whether this is good practice, I would say no. You have a single macro instantiating multiple variable... |
4,977,715 | 4,977,816 | Calculating and printing factorial at compile time in C++ | template<unsigned int n>
struct Factorial {
enum { value = n * Factorial<n-1>::value};
};
template<>
struct Factorial<0> {
enum {value = 1};
};
int main() {
std::cout << Factorial<5>::value;
std::cout << Factorial<10>::value;
}
above program computes factorial value during compile time. I want to pri... | The factorial can be printed in compiler-generated message as:
template<int x> struct _;
int main() {
_<Factorial<10>::value> __;
return 0;
}
Error message:
prog.cpp:14:32: error: aggregate ‘_<3628800> __’ has incomplete type and cannot be defined
_::value> __;
... |
4,977,726 | 4,977,916 | CPU cost order of magnitude for some basic operations | After answering to that SO question and being donwvoted I'd like to check something with you.
So as to have a draft idea of the cost of the code I write, I have the tendency to scale operations this way.
Heap allocation is around 1000 times slower than Stack allocation.
IO with screen/output is around 1000 times
slow... | The 1st point depends on a lot of things, really. If you run out of memory, then allocating something on the heap may take literally minutes. The stack, on the other hand, may already be allocated at that point.
The 2nd point depends on the terminal being used. Outputting to a DOS screen is one thing, outputting to a W... |
4,977,731 | 4,977,795 | stringstream to array | could you tell me, why is this wrong?
I have
mytype test[2];
stringsstream result;
int value;
for (int i=0; i<2; i++) {
result.str("");
(some calculating);
result<< value;
result>> test[i];
}
When I watch to test array - only first - test[0] - has correct value - every other test[1..x] has value 0
why i... | Try result.clear()ing your stringstream before flushing it with result.str(""). This sets it to a state of accepting inputs again after outputting the buffer.
#include <sstream>
using namespace std;
int main(){
int test[2];
stringstream result;
int value;
for (int i=0; i<2; i++) {
result.clear... |
4,978,032 | 4,978,087 | C++ Build warning in GCC ARM but not MS x86 | I use the Airplay SDK which is a platform for building C++ apps for smartphones. It also has a x86 simulator which uses MS Visual C++ IDE + compiler.
Now, I have this class :
namespace Fair {
class Bitmap : public Sprite {
public:
const CIw2DImage* const& getBitmapData() { return bitmapData; }; // wa... | You won't save any memory at all returning a reference, it's just a pointer internally. In addition, const occurs completely at compile-time, there's no reason for any temporary to be produced- and even if it was, a const reference to it would be valid.
That code looks terrible to me personally but it's not undefined i... |
4,978,126 | 5,026,116 | XML as Virtual registry makes the application work slow | I am building an "Application Virtualization" product. I use XML file as a virtual registry.
Virtual applications generated from my software accesses the virtual registry Xml.
It runs , however runs very slow.
I load and unload the XML on every Registry API calls, because multiple process threaded from the parent acce... | Its text to tree transformation time.
I managed this in my code by Loadaing and Parsing the XML in all processes, only after a write has occured in any one of the process.
|
4,978,302 | 4,978,346 | Besides accessibility, what else access-specifiers effects? | Besides the normal explenation of being visible or not to derived classes, is their any other difference?
If you make it more visible, is it taking more or less memory, does it slow thing down or...?
| Apart from the accessibility of members outside or to the derived classes, access specifiers might affect the object layout.
Quoting from my other answer:
Usually, memory address for data members increases in the order they're defined in the class . But this order may be disrupted at any place where the access-specifie... |
4,978,330 | 4,978,363 | c++ library with c interface | i need to write a library in c++ , usable by client to do some operations in a remote server. The only thing in the specific i haven't done yet it's: The c++ library need a C interface. Let me explain better:
From client using this lib i need to do call something like:
int operation(void* addr);
if int<0 error
and so..... | You can use the PIMPL idiom in the C wrapper. You provide a method YourClass_Create that internally calls the constructor (using new) and returns the pointer to your class instance; for the client code this will be just an opaque handle (it may be a typedef for void *), to be passed to every function of your C interfac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.