Skip to content

Instantly share code, notes, and snippets.

@SirLynix
Created February 17, 2019 18:26
Show Gist options
  • Save SirLynix/8ffb65bf6182de5d90d385f376c3ceda to your computer and use it in GitHub Desktop.
Save SirLynix/8ffb65bf6182de5d90d385f376c3ceda to your computer and use it in GitHub Desktop.
Cours sur les pointeurs en C et C++
// Exemple C++
#include <memory>
#include <iostream>
#include <string>
#include <vector>
#include <mutex>
class CopyWatcher
{
public:
CopyWatcher()
{
m_content = new int[500];
std::cout << this << ": default-constructed" << std::endl;
}
CopyWatcher(const CopyWatcher& rhs)
{
m_content = new int[500];
std::memcpy(m_content, rhs.m_content, sizeof(int) * 500);
std::cout << this << ": copy-constructed from " << &rhs << std::endl;
}
CopyWatcher(CopyWatcher&& rhs) noexcept :
m_content(rhs.m_content)
{
rhs.m_content = nullptr;
std::cout << this << ": move-constructed from " << &rhs << std::endl;
}
~CopyWatcher()
{
std::cout << this << ": destructed" << std::endl;
delete[] m_content;
}
CopyWatcher& operator=(const CopyWatcher& rhs)
{
delete[] m_content;
m_content = new int[500];
std::memcpy(m_content, rhs.m_content, sizeof(int) * 500);
std::cout << this << ": copy-assigned from " << &rhs << std::endl;
return *this;
}
CopyWatcher& operator=(CopyWatcher&& rhs) noexcept
{
m_content = rhs.m_content;
rhs.m_content = nullptr;
std::cout << this << ": move-assigned from " << &rhs << std::endl;
return *this;
}
private:
int* m_content;
};
void petiteFonction(std::unique_ptr<CopyWatcher> a);
class A
{
public:
virtual void print()
{
std::cout << "A" << std::endl;
}
};
class B : public A
{
public:
void print() override
{
std::cout << "B" << std::endl;
}
};
int main()
{
std::shared_ptr<CopyWatcher> ptr = std::make_shared<CopyWatcher>();
std::shared_ptr<CopyWatcher> ptr2 = std::make_shared<CopyWatcher>();
std::shared_ptr<CopyWatcher> ptr3 = ptr2;
// CopyWatcher a;
// CopyWatcher b(std::move(a));
// RAII = Resource Acquisition Is Initialization
// RRID = Resource Reclamation Is Destruction
std::cout << std::endl;
return 0;
}
void petiteFonction(std::shared_ptr<CopyWatcher> a)
{
std::cout << &*a << std::endl;
}
void print(const std::string& str)
{
std::cout << str << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment