- sziku69: Fűzzük össze a szavakat :)
- Luck Dragon: Asszociációs játék. :)
- pusszycat: JEYI - okos, színes, interaktív, ssd külső ház.
- Magga: PLEX: multimédia az egész lakásban
- eBay-es kütyük kis pénzért
- kraftxld: Untappd lista
- sziku69: Szólánc.
- MasterDeeJay: Gigabyte GA-B350M-D2 - AM4 lap 2016-ból amikor még nem volt Ryzen!
- sellerbuyer: Nem veszélytelen a RAM duplázás de vajon megéri?
- urandom0: Új kedvenc asztali környezetem, az LXQt
Új hozzászólás Aktív témák
-
cog777
senior tag
válasz
jattila48 #4467 üzenetére
Azt hittem azt kerdezed hogy csak a declaraciora vonatkozik az extern "c" vagy az implementaciora is.
A fenti peldaban mindkettot ajanljak, ha tobbfele forditot hasznalsz.Ha a valtozora kerdezel ra, akkor igen lehet hasznalni arra is, ugyanabbol a celbol.
Language linkage - cppreference.com -
cog777
senior tag
válasz
jattila48 #4465 üzenetére
Nem kotelezo, de az okosok azt irjak hogy erdemes lehet hasznalni.
Utolso elotti hozzaszolas.
"We had always only added extern "C" to the header definitions, but this allows the C++ code to implement the function with a different signature via overloading without errors and yet it doesn't mangle the symbol definition so at link times it uses this mismatching function. If the header and the definition both have extern "C" then a mismatched signature generates an error with Visual Studio 2017 and with g++ 5.4." -
cog777
senior tag
válasz
jattila48 #4463 üzenetére
Funkcio nevet c-vel kompatibilissa teszi. Jol jon ha a library-t hozza akarod forditani mas c++ forditoban keszult projektel vagy akar mas nyelvben pl python akarod hasznalni.
Minden c++ forditobak megvan a maga formatuma, c viszont kompatibilis.
linux alatt vannak parancsok amivel ezt meg tudod nezni ha erdekel. -
cog777
senior tag
https://godbolt.org/-ot nem is ismertem, asm-et mutat egy c++ programrol.
-
cog777
senior tag
Tobb megoldast kaptam, itt lehet elolvasni.
Lenyeg: van lehetoseg trukkozni, de az tenyleg trukkozes, inkabb template specializaciot valasztanek.Ez a megoldas tetszett jobban:
#include <fmt/format.h>
#include <array>
#include <cstddef>
#include <mutex>
enum class thread_safety_mode {
safe,
unsafe,
};
template <typename T, std::size_t Size, thread_safety_mode Mode>
class circular_buffer;
template <typename T, std::size_t Size>
class circular_buffer<T, Size, thread_safety_mode::unsafe> {
public:
// Push an item to the tail
bool push(const T& item) {
if (is_full()) return false;
buffer_[head_] = item;
head_ = (head_ + 1) % buffer_.size();
return true;
}
// Pop an item from the head
bool pop(T& item) {
if (is_empty()) return false;
item = buffer_[tail_];
tail_ = (tail_ + 1) % buffer_.size();
return true;
}
// Check if the buffer is full
bool is_full() const { return (head_ + 1) % buffer_.size() == tail_; }
// Check if the buffer is empty
bool is_empty() const { return head_ == tail_; }
private:
std::array<T, Size> buffer_;
std::size_t head_{0};
std::size_t tail_{0};
};
template <typename T, std::size_t Size>
class circular_buffer<T, Size, thread_safety_mode::safe> {
public:
bool push(const T& item) {
std::lock_guard<std::mutex> lk(m);
fmt::println("locked for push()");
return unsafe_buffer.push(item);
}
// Pop an item from the head
bool pop(T& item) {
std::lock_guard<std::mutex> lk(m);
fmt::println("locked for pop()");
return unsafe_buffer.pop(item);
}
// Check if the buffer is full
bool is_full() const {
std::lock_guard<std::mutex> lk(m);
fmt::println("locked for is_full()");
return unsafe_buffer.is_full();
}
// Check if the buffer is empty
bool is_empty() const {
std::lock_guard<std::mutex> lk(m);
fmt::println("locked for is_empty()");
return unsafe_buffer.is_empty();
}
private:
circular_buffer<T, Size, thread_safety_mode::unsafe> unsafe_buffer{};
mutable std::mutex m{};
};
auto main() -> int {
//
circular_buffer<int, 42, thread_safety_mode::safe> cb{};
cb.push(43);
cb.push(44);
cb.push(45);
int val;
cb.pop(val);
fmt::println("val: {}", val);
cb.pop(val);
fmt::println("val: {}", val);
cb.pop(val);
fmt::println("val: {}", val);
} -
cog777
senior tag
Masik kerdes.
Adja magat egy thread es egy nem thread safe verzioja a circual_buffer-nek.
Forditasi idoben meg tudom mondani hogy a mutex-es sorok letiltodjanak vagy engedelyezve legyenek template-et hasznalva?Valami ilyesmire gondoltam, ugyanakkor forditasi hibaim vannak:
#pragma once
#include <array>
#include <stddef.h>
#include <mutex>
enum class THREAD_SAFETY
{
THREAD_SAFE = 0,
NOT_THREAD_SAFE
};
template <typename T, size_t S, THREAD_SAFETY TH>
class circular_buffer
{
public:
explicit circular_buffer() {}
// Push an item to the tail
bool push(const T &item)
{
if constexpr (std::is_same<TH, THREAD_SAFETY::THREAD_SAFE>::value)
{
std::lock_guard<std::recursive_mutex> lk(m);
}
if (is_full())
return false;
buffer_[head_] = item;
head_ = (head_ + 1) % buffer_.size();
return true;
}
// Pop an item from the head
bool pop(T &item)
{
if constexpr (std::is_same<TH, THREAD_SAFETY::THREAD_SAFE>::value)
{
std::lock_guard<std::recursive_mutex> lk(m);
}
if (is_empty())
return false;
item = buffer_[tail_];
tail_ = (tail_ + 1) % buffer_.size();
return true;
}
// Check if the buffer is full
bool is_full() const
{
if constexpr (std::is_same<TH, THREAD_SAFETY::THREAD_SAFE>::value)
{
std::lock_guard<std::recursive_mutex> lk(m);
}
return (head_ + 1) % buffer_.size() == tail_;
}
// Check if the buffer is empty
bool is_empty() const
{
if constexpr (std::is_same<TH, THREAD_SAFETY::THREAD_SAFE>::value)
{
std::lock_guard<std::recursive_mutex> lk(m);
}
return head_ == tail_;
}
private:
std::array<T, S> buffer_;
size_t head_{0};
size_t tail_{0};
if constexpr (std::is_same<TH, THREAD_SAFETY::THREAD_SAFE>::value)
{
mutable std::recursive_mutex m;
}
};main.cpp-ben:
circular_buffer<int, 5, THREAD_SAFETY::THREAD_SAFE> buffer;
De sajnos hibakat ir ki:
/home/zoltan/dev/learning/CPP/algorithms/producer-consumer/circular_buffer.h:70:5: error: expected unqualified-id before ‘if’
70 | if constexpr (std::is_same<TH, THREAD_SAFETY::THREAD_SAFE>::value)
| ^~
/home/zoltan/dev/learning/CPP/algorithms/producer-consumer/circular_buffer.h: In member function ‘bool circular_buffer<T, S, TH>::push(const T&)’:
/home/zoltan/dev/learning/CPP/algorithms/producer-consumer/circular_buffer.h:21:66: error: type/value mismatch at argument 1 in template parameter list for ‘template<class, class> struct std::is_same’
21 | if constexpr (std::is_same<TH, THREAD_SAFETY::THREAD_SAFE>::value)Masreszt nem vagyok biztos hogy a constexpr if-ek valodi blokkent mukodnek, tehat a lock_guard mukodni fog-e...
-
cog777
senior tag
Le tudna valaki csekkolni ezt a kodot? Tok mas teruleten dolgoztam mostanaban es radobbentem, hogy bizonytalan vagyok most ebben az alap kerdesben. Consumer-producer, thread safe circular buffer-rel + recursize mutex.
Lefordul, mukodik crash nelkul, de kivancsi vagyok hogy elszabtam-e valamit... koszi elore is.
Circular buffer kodja:
circular_buffer.h#pragma once
#include <array>
#include <stddef.h>
#include <mutex>
template <typename T, size_t S>
class circular_buffer
{
public:
explicit circular_buffer() {}
// Push an item to the tail
bool push(const T &item)
{
std::lock_guard<std::recursive_mutex> lk(m);
if (is_full())
return false;
buffer_[head_] = item;
head_ = (head_ + 1) % buffer_.size();
return true;
}
// Pop an item from the head
bool pop(T &item)
{
std::lock_guard<std::recursive_mutex> lk(m);
if (is_empty())
return false;
item = buffer_[tail_];
tail_ = (tail_ + 1) % buffer_.size();
return true;
}
// Check if the buffer is full
bool is_full() const
{
std::lock_guard<std::recursive_mutex> lk(m);
return (head_ + 1) % buffer_.size() == tail_;
}
// Check if the buffer is empty
bool is_empty() const
{
std::lock_guard<std::recursive_mutex> lk(m);
return head_ == tail_;
}
private:
std::array<T, S> buffer_;
size_t head_{0};
size_t tail_{0};
mutable std::recursive_mutex m;
};main.cpp
#include "circular_buffer.h"
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
circular_buffer<int, 5> buffer;
std::mutex mtx; // Mutex for protecting shared data
std::condition_variable empty, full; // Condition variables
void producer(int loops)
{
for (int i = 0; i < loops; ++i)
{
std::unique_lock<std::mutex> lock(mtx);
while (buffer.is_full())
{
empty.wait(lock); // Wait if buffer is full
}
buffer.push(i);
full.notify_one(); // Signal that buffer is not empty
std::cout << "Produced: " << i << std::endl;
}
}
void consumer(int loops)
{
for (int i = 0; i < loops; ++i)
{
std::unique_lock<std::mutex> lock(mtx);
while (buffer.is_empty())
{
full.wait(lock); // Wait if buffer is empty
}
int tmp;
buffer.pop(tmp);
empty.notify_one(); // Signal that buffer is not full
std::cout << "Consumed: " << tmp << std::endl;
}
}
int main()
{
int loops = 10;
std::thread prodThread(producer, loops);
std::thread consThread(consumer, loops);
prodThread.join();
consThread.join();
return 0;
} -
cog777
senior tag
válasz
Tomi_78 #4449 üzenetére
Koszi, az elsot nem tolti be. Igen, bar nekem evekkel korabban a Google sokszor nagyon alap kvizeket adott ki, ezt pl 25-bol 24-et sikerult eltalalnom, tul alap.
Most rakeresve "c++ quiz" kifejezesre, tobb tesztet talaltam, pl c++20 teszt. Bocs a zajt.
[link] , [link] , [link] -
cog777
senior tag
Tud valaki c++ teszteket? Lehetoleg advanced level-t vagy magasabbat, akarok allas interjuzni a kozeljovoben es bizonyos dolgokban berozsdasodtam. Linkedin-en van par kurzus c++20-al kapcsolatban, de ugy erzem jo lenne teszteket csinalgatnom.
-
cog777
senior tag
cmake kerdesem van. Egy eleg nagy projektben (600 cmakefiles) kell egy uj ficsort keszitenem. A problema a korkoros dependency.
Szoval protokol modul hasznalta a driver-t. Driver object-kent volt, protocol static-kent forditva.
Most az uj ficsor a driver-bol hasznal protokolt. Igy cmake kiirta hogy ez biza cyclic dependency es legalabb 1 target nem static.Valoban, driver nem az.
Nosza allittsuk at object-rol static-ra.
Lefordul, orom bodotta.
Vazz, a ficsor kodja lefordul, latom a logban de nem linkelodik ossze es nem is tudok breakpoint-ot tenni ra. Mikor objectkent volt linkelve akkor breakpoint mukodott.
Persze, megallapitottuk hogy ezt a reszt ujra kellene strukturalni, de most 1 ideiglenes megoldast kell csinalnom.
Megkoszonom ha valaki hozza tudna szolni a szituaciohoz es adni tanacsot -
cog777
senior tag
válasz
bandi0000 #2423 üzenetére
C-ben azert nehezebb programozni mint C++-ban. Biztos hogy C-ben akarod megcsinalni? Ugyanis C-ben nagyon kell figyelni dolgokra, pl ha elszursz egy pointert akkor megjosolhatatlan lehet a program viselkedese, vagy ha nem inicialialsz 0-val egy teruletet ahol string-et tarolsz akkor a printf tovabbi karaktereket is kiirat mert nem talalja a 0-a veget.
for ciklust 1-es index-el kezdted, igy akartad?
fscanf beolvassa ugyan az ertekeket es a string-et is de mi a garancia hogy a string pont akkora a szovegben mint a memoria teruleted:char re[3][7]? Mivel csak 7 karaktert foglaltal le es nem 8at azert hogy 0-t rakj a vegere ezert a printf tovabb irja a szoveget mint 7 karakter.printf utolso parametere nem &re[ I ]hanem csak re[ i ]
"Elvileg ennek tökéletesen kellene mennie"
Bocsanat, nem kotekedesnek szanom, de szerintem a buffer overflow betoreseket is ezek a kielentesek okozzakUgy erdemes programot kesziteni hogy torekszel arra hogy a hiba lehetosegek szamat minimalisra szoritsd.
Hacsak nem kifejezetten C-t akarsz tanulni linux kernel driver iras miatt, akkor inkabb hasznalj C++-t modern technologiakkal:std::array ahol beallitod a meretet a tomb-nek, .at(index) -el elered az elemet (es ha tul index-elsz akkor egybol latod mi a baj), komplett sort olvasnek be a helyedben es std::string-et hasznalnek majd onnan masolnam at az egyes reszeket struct-t ba mivel ezek a sorok egybe tartoznak.
Remelem sikerul atirnod! Sok sikert!
-
cog777
senior tag
Udv!
A memoria szivargas kereso g++ alatt remekul mukodik az std::map sajat allocatorral. Viszont Blackberry alatt a qcc nem birja leforditani.
Itt a cod:
Igy hasznalom:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <map>
#include "allocator.h"
#include "mynew.h"
#undef new
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
typedef struct node node_t;
struct node {
void * ptr;
bool array;
unsigned int line;
const char *file;
};
std::map<void *, node_t *, std::less<void *>,
fooStdAllocator<std::pair<void *, node_t *> > > booking;Hibauzenetek:
/Applications/bbndk/target_10_1_0_1020/qnx6/usr/include/cpp/xtree:174:51: error: no type named 'difference_type' in 'std::_Tree<std::_Tmap_traits<void*, node*, std::less<void*>, fooStdAllocator<std::pair<void*, node*> >, false> >::allocator_type {aka class fooStdAllocator<std::pair<void* const, node*> >}'
...
/Applications/bbndk/target_10_1_0_1020/qnx6/usr/include/cpp/xtree:189:8: error: no type named 'difference_type' in 'std::_Tmap_traits<void*, node*, std::less<void*>, fooStdAllocator<std::pair<void*, node*> >, false>::allocator_type {aka class fooStdAllocator<std::pair<void* const, node*> >}'
../src/mynew.cpp: In function 'void removeFromList(void*, bool)':
../src/mynew.cpp:42:64: error: conversion from 'std::_Tree<std::_Tmap_traits<void*, node*, std::less<void*>, fooStdAllocator<std::pair<void*, node*> >, false> >::iterator' to non-scalar type 'std::map<void*, node*>::iterator {aka std::_Tree<std::_Tmap_traits<void*, node*, std::less<void*>, std::allocator<std::pair<void* const, node*> >, false> >::iterator}' requested
../src/mynew.cpp:44:28: error: no match for 'operator!=' in 'itr != booking.std::map<void*, node*, std::less<void*>, fooStdAllocator<std::pair<void*, node*> > >::<anonymous>.std::_Tree<_Traits>::end [with _Traits = std::_Tmap_traits<void*, node*, std::less<void*>, fooStdAllocator<std::pair<void*, node*> >, false>]()'
...
../src/mynew.cpp:46:26: error: no matching function for call to 'std::map<void*, node*, std::less<void*>, fooStdAllocator<std::pair<void*, node*> > >::erase(std::map<void*, node*>::iterator&)'Ha van valakinek otlete, orulnek neki ha megosztana hogy merre induljak el.
-
-
cog777
senior tag
válasz
WonderCSabo #2135 üzenetére
Találkoztam már vele igen, de pár platform sajnos nem támogatja.. így ezt találtam ki. Még fejlesztenem kell rajta, rendezett listát akarok csinálni és bináris kereséssel hamarabb megtalálni a keresett pointert. Fákat nem hiszem hogy akarok implementálni.
-
cog777
senior tag
válasz
D®. GeNy@ #2132 üzenetére
Hello!
Ez azt jelenti hogy a programnak vissza kellene adni a keretprogramnak 2x tabot és 1 entert? (Nem teljesen világos a feladat)
TAB billentyű 2x bevitel egymás után, majd ezután egy ENTER parancs küldése.
TAB-ot /t
Entert a /n jelöli.Tehát [link] a példa szerint, neked ezt kellene írnod:
cout << "/t/t/n";
(Nézd meg a teljes példát)
-
cog777
senior tag
Üdv!
Ha valakit érdekel, egyszerű de nagyszerű memória foglalás/felszabadítás nyilvántartót írtam (interneten található példákat felhasználva), segítségével a memory leak-ot lehet könnyen detektálni. Igaz, Qt-s GUI programokra hegyeztem ki, de át lehet alkalmazni nem Qt-s programokra is. Csak be kell illeszteni a kívánt forráskód include blokkjának a végére a #include "mynew.h"-t. Illetve a program végén meghívni a printList(); deleteList(); függvényeket.
https://github.com/zhanisch/DetectingMemLeak.git
Git-tel letölteni:
git clone https://github.com/zhanisch/DetectingMemLeak.git
Futtatva:
Starting /home/zhanisch/documents/QtProjects/build-DetectingMemLeak-Desktop_Qt_5_0_2_GCC_32bit-Debug/DetectingMemLeak...
Not relased object at: 162713376, file: ../DetectingMemLeak/mainwindow.cpp, line: 19
Not relased object at: 162711392, file: ../DetectingMemLeak/mainwindow.cpp, line: 23
/home/zhanisch/documents/QtProjects/build-DetectingMemLeak-Desktop_Qt_5_0_2_GCC_32bit-Debug/DetectingMemLeak exited with code 0 -
cog777
senior tag
Köszönöm a gyors válaszokat!!!
-
cog777
senior tag
Sziasztok!
Most nézem át a c++ operátor overloading-ját, van két megoldás:
class Point
{
public:
Point(int x, int y) {Point::x=x;Point::y=y;}
Point operator+(Point &p) {return Point(x+p.x, y+p.y);}private:
int x,y;
}A kérdésem:
"Point operator+(Point &p) {return Point(x+p.x, y+p.y);}" Miért lehet elérni a "p.x"-et??? (illetve a p.y-t?) (Az adatrejtés elve miatt kérdezem, hiszen private )A másik megolds szinte ugyanez:
class Point
{
public:
Point(int x, int y){Point::x=x;Point::y=y;}
friend Point operator+(Point &p, Point &q) {return Point(q.x+p.x, q.y+p.y);}private:
int x,y;
}Itt már értem, hiszen a friend el tudja érni a private adatokat!
Új hozzászólás Aktív témák
Hirdetés
● ha kódot szúrsz be, használd a PROGRAMKÓD formázási funkciót!
- Újszerű Lenovo Thinkpad T16 gen2 (13.gen Core I7 32Gb DDR5 1 Tb SSD) MAGYAR laptop 2 év garancia!!
- Asus Tuf Gaming F15 újszerű garanciális LEGOLCSÓBBAN A NETEN!
- Gamer PC - i5 12400f, RTX 3080 és 32gb RAM + GARANCIA
- Apple AirPods Max (2024) 2027.01.27. Apple jótállás iSTYLE jótállás
- Switch 2 2027.07.24-ig garanciás, dobozában, karcmentes állapotban eladó!
- PlayStation Network (PSN) ajándékkártyák, feltöltőkártyák áron alul!
- GYÖNYÖRŰ iPhone 11 Pro 256GB Midnight Green -1 ÉV GARANCIA - Kártyafüggetlen, MS2253,95% Akkumulátor
- Bomba ár! HP ProBook 650 G4 - i5-8GEN I 8GB I 256GB SSD I 15,6" FHD I Cam I W11 I Garancia!
- GYÖNYÖRŰ iPhone 14 Pro Max 256GB Deep Purple -1 ÉV GARANCIA - Kártyafüggetlen, MS3419
- BESZÁMÍTÁS! GIGABYTE A520M R5 3600 16GB DDR4 512GB SSD RX 6600 8GB Rampage SHIVA ADATA 600W
Állásajánlatok
Cég: CAMERA-PRO Hungary Kft.
Város: Budapest
Cég: PCMENTOR SZERVIZ KFT.
Város: Budapest